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

คุณสมบัติ captionSide ของ HTML DOM Style: ตำแหน่งคำอธิบายตาราง

คุณสมบัติ captionSide ใช้สำหรับกำหนดหรือดึงค่าตำแหน่งของ <caption> (คำอธิบายตาราง) รองรับเฉพาะตำแหน่งแนวตั้ง: บน (top) หรือ ล่าง (bottom)

ไวยากรณ์ (Syntax)

object.style.captionSide = "top|bottom|initial|inherit"

ค่าที่รองรับ

ค่าคำอธิบาย
topวาง caption เหนือตาราง (ค่าเริ่มต้น)
bottomวาง caption ใต้ตาราง
initialตั้งค่ากลับเป็นค่าเริ่มต้น (top)
inheritสืบทอดจากพาเรนต์

ตัวอย่างการใช้งาน

<!DOCTYPE html>
<html>
<head>
<style>
  #t1 {
    caption-side: bottom;
    border: 2px dashed black;
  }
  td {
    border: 2px solid blue;
    padding: 8px;
  }
  caption {
    font-size: 24px;
    font-weight: bold;
    padding: 10px;
  }
</style>
<script>
  function changeCaptionPosition() {
    document.getElementById("t1").style.captionSide = "top";
    document.getElementById("Sample").innerHTML = "ตำแหน่ง caption เปลี่ยนเป็น top แล้ว";
  }
</script>
</head>
<body>
<table id="t1">
  <caption>Demo Caption</caption>
  <tr><th>หัวข้อ 1</th><th>หัวข้อ 2</th></tr>
  <tr><td>ข้อมูล...</td><td>ข้อมูล...</td></tr>
  <tr><td>ข้อมูล...</td><td>ข้อมูล...</td></tr>
</table>
<p>คลิกปุ่มเพื่อเปลี่ยนตำแหน่ง caption ของตารางด้านบน</p>
<button onclick="changeCaptionPosition()">เปลี่ยนตำแหน่ง Caption</button>
<p id="Sample"></p>
</body>
</html>

ผลลัพธ์

ก่อน: Caption อยู่ใต้ตาราง (bottom)
หลัง: Caption อยู่เหนือตาราง (top)

คุณสมบัติตารางที่เกี่ยวข้อง

คุณสมบัติคำอธิบาย
borderCollapsecollapse / separate (รวม/แยกขอบ)
borderSpacingระยะห่างเซลล์ (เมื่อ separate)
emptyCellsshow / hide (เซลล์ว่าง)
tableLayoutauto / fixed (อัลกอริทึม layout)
captionSideตำแหน่ง caption (คุณสมบัตินี้)

การจัดสไตล์ Caption เพิ่มเติม

caption {
  caption-side: bottom;
  text-align: left;        /* จัดชิดซ้าย */
  font-weight: bold;
  color: #666;
  padding: 0.5rem;
  background: #f5f5f5;     /* พื้นหลัง */
  border: 1px solid #ddd;
  border-bottom: none;     /* ต่อกับตาราง */
}

ความเข้าถึง (Accessibility)

  • <caption> สำคัญสำหรับ Screen Reader - อธิบายเนื้อหาตาราง
  • ควรวางไว้เป็นลูกแรกของ <table> เสมอ
  • ไม่ควรใช้ <th> แทน caption

การรองรับเบราว์เซอร์

รองรับในทุกเบราว์เซอร์สมัยใหม่ (IE8+)