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

เหตุการณ์เมื่อปรับขนาดหน้าต่างเบราวเซอร์ใน JavaScript

เหตุการณ์ resize

เหตุการณ์ที่เกิดขึ้นเมื่อผู้ใช้ปรับขนาดหน้าต่างเบราวเซอร์คือ resize สามารถผูก (attach) ไว้ที่อ็อบเจกต์ window ได้

วิธีการใช้งาน

// วิธีที่ 1: ใช้ addEventListener (แนะนำ)
window.addEventListener("resize", function() {
  console.log("ขนาดเปลี่ยน: " + window.outerWidth + "x" + window.outerHeight);
});

// วิธีที่ 2: ใช้ onresize property
window.onresize = function() {
  // โค้ดที่นี่
};

// วิธีที่ 3: ใน HTML attribute (ไม่แนะนำสำหรับโค้ดใหญ่)
<body onresize="resizeFunction()">

ตัวอย่างโค้ดสมบูรณ์

<!DOCTYPE html>
<html>
<head>
  <style>
    #sizeDisplay {
      padding: 15px;
      background: #f5f5f5;
      border: 1px solid #ddd;
      font-family: monospace;
      margin: 20px 0;
    }
  </style>
  <script>
    function updateSizeDisplay() {
      var display = document.getElementById("sizeDisplay");
      var width = window.outerWidth;
      var height = window.outerHeight;
      var innerWidth = window.innerWidth;
      var innerHeight = window.innerHeight;
      
      display.innerHTML = 
        "outerWidth: " + width + "px
" + "outerHeight: " + height + "px
" + "innerWidth: " + innerWidth + "px
" + "innerHeight: " + innerHeight + "px"; } // ผูกเหตุการณ์ window.addEventListener("resize", updateSizeDisplay); // เรียกครั้งแรกเพื่อแสดงค่าเริ่มต้น updateSizeDisplay(); </script> </head> <body> <p>ลองปรับขนาดหน้าต่างเบราวเซอร์ดูสิ</p> <div id="sizeDisplay"></div> </body> </html>

ความแตกต่างระหว่าง outer และ inner

คุณสมบัติ คำอธิบาย
window.outerWidth / outerHeight ขนาดทั้งหมดของหน้าต่างเบราวเซอร์ รวมแถบเครื่องมือ, scrollbar, ขอบหน้าต่าง
window.innerWidth / innerHeight ขนาดบริเวณแสดงผลเว็บเพจ (viewport) ไม่รวม UI ของเบราวเซอร์

แนวทางปฏิบัติที่ดี (Best Practices)

  • Debounce/Throttle: เหตุการณ์ resize ยิงบ่อยมาก ควรใช้ debounce เพื่อประสิทธิภาพ
  • หลีกเลี่ยงการคำนวณหนักหรือ layout thrashing ใน handler
  • พิจารณาใช้ ResizeObserver สำหรับการติดตามขนาดอิลิเมนต์เฉพาะ (แทน window)

ตัวอย่าง Debounce

function debounce(func, wait) {
  var timeout;
  return function() {
    var context = this, args = arguments;
    clearTimeout(timeout);
    timeout = setTimeout(function() {
      func.apply(context, args);
    }, wait);
  };
}

var optimizedResize = debounce(function() {
  console.log("Resize settled:", window.innerWidth, "x", window.innerHeight);
  // ทำงานที่นี่ เช่น recalculate layout
}, 150);

window.addEventListener("resize", optimizedResize);

ResizeObserver (สมัยใหม่)

สำหรับติดตามขนาดของอิลิเมนต์เฉพาะ (ไม่ใช่ window ให้ใช้ ResizeObserver):

var observer = new ResizeObserver(function(entries) {
  for (var entry of entries) {
    console.log("Element size changed:", entry.contentRect.width, "x", entry.contentRect.height);
  }
});

observer.observe(document.querySelector(".my-element"));