Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

ออบเจ็กต์ Figcaption ใน HTML DOM

ออบเจ็กต์ Figcaption ใน HTML DOM ใช้แทนองค์ประกอบ HTML5 <figcaption> ใช้สำหรับสร้างหรือเข้าถึง figcaption ด้วย createElement() และ getElementById()

ไวยากรณ์ (Syntax)

การสร้างออบเจ็กต์ Figcaption:

var figcaption = document.createElement("FIGCAPTION");

ตัวอย่าง

ตัวอย่างการเพิ่ม caption ให้รูปภาพใน figure:

<!DOCTYPE html>
<html>
<head>
<script>
  function createCaption() {
    var caption = document.createElement("FIGCAPTION");
    var text = document.createTextNode("Learn Java Servlets");
    caption.appendChild(text);
    
    var figure = document.getElementById("Figure1");
    figure.appendChild(caption);
  }
</script>
</head>
<body>
<h2>Figcaption Object</h2>
<p>คลิกปุ่มด้านล่างเพื่อสร้าง caption ให้รูปภาพข้างล่าง</p>
<button onclick="createCaption()">CREATE</button>
<figure id="Figure1">
  <img src="https://www.tutorialspoint.com/servlets/images/servlets-mini-logo.jpg" alt="Servlets" width="250" height="200">
</figure>
</body>
</html>

ผลลัพธ์

เมื่อโหลดหน้าเว็บจะแสดงรูปภาพใน figure และปุ่ม "CREATE"

เมื่อคลิกปุ่ม "CREATE" จะเพิ่มข้อความ "Learn Java Servlets" เป็น caption ใต้รูปภาพ

คำอธิบายโค้ด

  • มี <figure id="Figure1"> พร้อม <img> อยู่แล้ว
  • สร้างปุ่ม "CREATE" เรียกใช้ createCaption() เมื่อคลิก
  • ฟังก์ชัน createCaption() สร้าง <figcaption> เก็บใน caption
  • สร้างโหนดข้อความ "Learn Java Servlets" ผูกเข้ากับ caption
  • ดึง figure ด้วย getElementById("Figure1") แล้วต่อท้าย caption เข้าไป
  • <figcaption> ต้องอยู่ภายใน <figure> เป็นลูกแรกหรือลูกสุดท้าย