Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách thiết lập thứ tự flex item tương đối với các item khác với JavaScript

Thuộc tính order (CSS order) kiểm soát thứ tự hiển thị trực quan của flex items trong container. Giá trị mặc định là 0. Số âm hiển thị trước, số dương sau.

Ví dụ minh họa

Ba DIV ban đầu theo thứ tự HTML. Nhấn nút để sắp xếp lại: DIV2 → DIV3 → DIV1:

<!DOCTYPE html>
<html>
<head>
  <style>
    #box {
      border: 1px solid #000;
      width: 420px;
      height: 150px;
      display: flex;
    }
    #box div {
      height: 80px;
      width: 80px;
    }
  </style>
</head>
<body>
  <div id="box">
    <div style="background-color:orange;" id="myID1">DIV1</div>
    <div style="background-color:blue;" id="myID2">DIV2</div>
    <div style="background-color:yellow;" id="myID3">DIV3</div>
  </div>
  <button onclick="display()">Thiết lập</button>
  <script>
    function display() {
      document.getElementById("myID1").style.order = "3";
      document.getElementById("myID2").style.order = "1";
      document.getElementById("myID3").style.order = "2";
    }
  </script>
</body>
</html>

Lưu ý

  • order chỉ ảnh hưởng thứ tự hiển thị, không thay đổi DOM order (tab index, screen reader vẫn theo DOM).
  • Không ảnh hưởng đến flex-direction: row-reverse hoặc column-reverse – chúng đảo ngược sau khi áp dụng order.
  • Dùng cho responsive: thay đổi bố cục mobile/desktop mà không đổi HTML.