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

Đối tượng HTML DOM Figure

Đối tượng Figure trong HTML DOM đại diện cho phần tử <figure> (HTML5), dùng để gom nhóm nội dung tự chứa như hình ảnh, sơ đồ, mã code, v.v. thường đi kèm <figcaption>. Có thể tạo và truy xuất động bằng JavaScript.

Cú pháp

Tạo đối tượng Figure:

var figureElement = document.createElement("FIGURE");

Ví dụ

Ví dụ tạo động figure chứa hình ảnh:

<!DOCTYPE html>
<html>
<head>
<script>
  function createFigure() {
    var fig = document.createElement("FIGURE");
    fig.setAttribute("id", "Figure1");
    document.body.appendChild(fig);
    var img = document.createElement("IMG");
    img.setAttribute("src", "https://www.tutorialspoint.com/servlets/images/servlets-mini-logo.jpg");
    img.setAttribute("width", "250");
    img.setAttribute("height", "200");
    img.setAttribute("alt", "Tháp Eiffel");
    fig.appendChild(img);
  }
</script>
</head>
<body>
<h2>Đối tượng HTML DOM Figure</h2>
<button onclick="createFigure()">TẠO</button><br><br>
</body>
</html>

Kết quả

Ban đầu chỉ có nút "TẠO".

Sau khi nhấn nút, hình ảnh logo Servlets (250x200px) xuất hiện bên trong phần tử figure có id="Figure1".

Giải thích

  • Nút "TẠO" gọi hàm createFigure().
  • Hàm tạo <figure>, đặt id="Figure1", gắn vào body.
  • Tạo <img>, đặt các thuộc tính src, width, height, alt qua setAttribute().
  • Gắn <img> vào <figure> bằng appendChild().