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

วิธีดึงตำแหน่ง Element เทียบ Floating Objects ด้วย clear Property ใน JavaScript

Property style.clear ควบคุมพฤติกรรมของ Element เทียบกับ Floating Elements (float: left/right) ไม่ได้ "ดึงตำแหน่ง" แต่ "กำหนดกฎการวาง"

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

<!DOCTYPE html>
<html>
  <head>
    <style>
      img { float: left; }
    </style>
  </head>
  <body>
    <img src="https://www.tutorialspoint.com/videotutorials/images/tutor_connect_home.jpg" width="170" height="150">
    <p id="myP">Demo content! ... (long text)</p>
    <button type="button" onclick="display()">Click</button>
    <script>
      function display() {
        document.getElementById("myP").style.clear = "left";
      }
    </script>
  </body>
</html>

ค่าของ clear Property

ค่าความหมาย
noneDefault: ขึ้นติด Floating Element ได้ (ถ้าพอ)
leftเลื่อนลงจนกว่าจะไม่มี Float ด้านซ้าย
rightเลื่อนลงจนกว่าจะไม่มี Float ด้านขวา
bothเลื่อนลงจนกว่าจะไม่มี Float ทั้งสองด้าน
inline-start/endLogical Properties (RTL/LTR Aware)

การทำงานในตัวอย่าง

  1. รูปภาพ float: left อยู่ซ้าย
  2. <p> ขึ้นติดข้างขวารูป (Wrap Around)
  3. กดปุ่ม → clear: left → <p> โดนผลักลงมาใต้รูปภาพ

Clearfix Pattern (สมัยใหม่)

/* แทนที่จะใช้ clear บน Element ถัดไป ให้ Clear บน Container */
.container::after {
  content: "";
  display: table;
  clear: both;
}

/* หรือ Modern */
.container {
  display: flow-root; /* สร้าง BFC เอง */
}

แก้ไขข้อมูลต้นฉบับ: คำอธิบายเดิม "return the position of the element relative to floating objects" ผิด — clear ไม่ได้ Return Position แต่ Control Layout Behavior