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

วิธีตั้งค่าความกว้างคอลัมน์และจำนวนคอลัมน์พร้อมกันด้วย JavaScript

บทนำ

Property columns ใน JavaScript เป็น shorthand ของ column-width และ column-count ช่วยกำหนดเลย์เอาต์หลายคอลัมน์ในคำสั่งเดียว

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

<!DOCTYPE html>
<html>
<head>
  <style>
    #myID {
      column-count: 4;
      column-rule: 4px solid yellow;
    }
  </style>
</head>
<body>
  <p>คลิกเพื่อเปลี่ยนจำนวนคอลัมน์เป็น 2 และตั้งค่าความกว้างขั้นต่ำ</p>
  <button onclick="display()">เปลี่ยนจำนวนคอลัมน์และตั้งค่าขนาด</button>
  <div id="myID">
    This is demo text. This is demo text. This is demo text. This is demo text.
    This is demo text. This is demo text. This is demo text. This is demo text.
    This is demo text. This is demo text. This is demo text. This is demo text.
    This is demo text. This is demo text. This is demo text. This is demo text.
    This is demo text. This is demo text. This is demo text. This is demo text.
    This is demo text. This is demo text. This is demo text. This is demo text.
  </div>
  <script>
    function display() {
      document.getElementById("myID").style.columns = "70px 2";
    }
  </script>
</body>
</html>

รูปแบบ Syntax

element.style.columns = "column-width column-count";

คำอธิบาย

  • "70px 2" - ความกว้างขั้นต่ำ 70px, จำนวนคอลัมน์สูงสุด 2
  • เบราว์เซอร์จะปรับจำนวนคอลัมน์อัตโนมัติตามพื้นที่ แต่ไม่เกิน 2 คอลัมน์
  • ลำดับไม่สำคัญ: "2 70px" ก็ได้

ค่าที่ใช้ได้

ค่าคำอธิบาย
autoค่าเริ่มต้น (column-width: auto, column-count: auto)
<length>column-width (ความกว้างขั้นต่ำ)
<integer>column-count (จำนวนคอลัมน์สูงสุด)
<length> <integer>ทั้งคู่

Properties แยกกัน

// แยกตั้งค่า
element.style.columnWidth = "100px";
element.style.columnCount = 3;

// Column gap (ระยะห่างคอลัมน์)
element.style.columnGap = "20px";

// Column rule (เส้นคั่น)
element.style.columnRule = "2px solid #ccc";

Responsive Columns

// ใช้ media query ร่วมกับ JS
if (window.innerWidth < 768) {
  element.style.columns = "100% 1"; // 1 คอลัมน์บนมือถือ
} else {
  element.style.columns = "300px 3"; // 3 คอลัมน์บนเดสก์ท็อป
}