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

วิธีตั้งค่าตำแหน่ง Table Caption ด้วย JavaScript

ใช้ Property captionSide (ไม่ใช่ borderWidth ตามต้นฉบับ) เพื่อตั้งค่าตำแหน่ง Caption ของ Table

ตัวอย่างโค้ด

<!DOCTYPE html>
<html>
  <body>
    <table id="newTable" border="2">
      <caption id="newCaption">Employee Details</caption>
      <tr><th>EmpID</th><th>EmpName</th><th>EmpDept</th></tr>
      <tr><td>001</td><td>Amit</td><td>IT</td></tr>
      <tr><td>002</td><td>John</td><td>Finance</td></tr>
      <tr><td>003</td><td>David</td><td>Marketing</td></tr>
    </table>
    <br>
    <button onclick="display()">Click to change caption position</button>
    <script>
      function display() {
        document.getElementById("newCaption").style.captionSide = "bottom";
      }
    </script>
  </body>
</html>

ค่าของ captionSide

ค่าตำแหน่ง
topด้านบน Table (Default)
bottomด้านล่าง Table
inheritสืบทอดจาก Parent

คำอธิบาย

  • captionSide เป็น CSS Property ของ <caption> Element
  • ้document.getElementById("newCaption").style.captionSide = "bottom" — ย้าย Caption ไปด้านล่าง
  • แก้ไขข้อมูลต้นฉบับ: ระบุว่าเป็น borderWidth property — ผิด ต้องเป็น captionSide

การใช้งานเพิ่มเติม

// Toggle Caption Position
const caption = document.querySelector('caption');
caption.style.captionSide = caption.style.captionSide === 'bottom' ? 'top' : 'bottom';

// ด้วย CSS Class (แนะนำ)
caption.classList.toggle('caption-bottom');

// CSS
.caption-bottom { caption-side: bottom; }