Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> HTML

Đối tượng Input Image trong HTML DOM

Đối tượng Input Image đại diện cho <input type="image"> - nút submit dạng hình ảnh. Khi nhấp, nó gửi form kèm tọa độ nhấp chuột (x, y) relative đến góc trên-trái của ảnh.

Tạo input image động

var imgInput = document.createElement("INPUT");
imgInput.setAttribute("type", "image");
imgInput.setAttribute("src", "url_anh.jpg");

Các thuộc tính chính

Thuộc tínhMô tả
altVăn bản thay thế (bắt buộc cho accessibility).
autofocusTự động focus khi tải trang.
defaultValueGiá trị mặc định (ít dùng cho type=image).
disabledVô hiệu hóa nút.
formForm chứa nút (chỉ đọc).
formActionGhi đè action của form khi submit bằng nút này.
formEnctypeGhi đè enctype của form.
formMethodGhi đè method của form (GET/POST).
formNoValidateBỏ qua validation form khi submit bằng nút này.
formTargetGhi đè target của form (_blank, _self...).
heightChiều cao hiển thị ảnh (px).
nameTên nút (gửi kèm tọa độ x.y).
srcURL hình ảnh hiển thị.
typeLuôn là "image" (chỉ đọc).
valueGiá trị ẩn (ít dùng).
widthChiều rộng hiển thị ảnh (px).

Ví dụ: Tạo nút submit dạng ảnh

<!DOCTYPE html>
<html>
<head>
    <style>
        body { text-align: center; background: #363946; color: white; font-family: sans-serif; padding: 20px; }
        .btn {
            background-color: #dc3545; border: none; color: white;
            padding: 10px 20px; border-radius: 25px; width: 60%;
            margin: 20px auto; display: block; cursor: pointer;
        }
    </style>
</head>
<body>
    <h1>Ví dụ DOM Input Image Object</h1>
    <button onclick="createImageBtn()" class="btn">Tạo nút submit dạng ảnh</button>
    <script>
        function createImageBtn() {
            var imgInput = document.createElement("INPUT");
            imgInput.setAttribute("type", "image");
            imgInput.setAttribute("src", "https://www.tutorialspoint.com/jdbc/images/jdbc-mini-logo.jpg");
            imgInput.setAttribute("alt", "Submit");
            imgInput.style.width = "100px";
            document.body.appendChild(imgInput);
        }
    </script>
</body>
</html>

Kết quả

Trước khi nhấn:

Đối tượng Input Image trong HTML DOM

Sau khi nhấn - nút submit dạng ảnh JDBC logo:

Đối tượng Input Image trong HTML DOM

⚠️ Đặc điểm quan trọng:
  • Gửi form kèm name.x và name.y (tọa độ nhấp).
  • Phải có thuộc tính alt để tuân thủ accessibility.
  • Thuộc tính formAction, formMethod... cho phép một form có nhiều nút submit đến endpoint khác nhau.