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

เหตุการณ์ onresize: รันสคริปตเมื่อปรับขนาดหน้าต่างเบราว์เซอร์

เหตุการณ์ onresize จะถูกกระตุ้นเมื่อขนาดหน้าต่างเบราว์เซอร์ (Viewport) เปลี่ยนแปลง ใช้สำหรับปรับ Layout, เรียกคำนวณใหม่, หรืออัปเดต UI ที่ต้องรู้ขนาดจอ

ตัวอย่างการใช้งาน

<!DOCTYPE html>
<html>
<body onresize="display()">
    <p>ลองปรับขนาดหน้าต่างเบราว์เซอร์เพื่อทดสอบเหตุการณ์</p>
    <div id="size" style="padding: 10px; background: #f0f0f0; margin-top: 10px;">
        ขนาด: <span id="w">-</span> x <span id="h">-</span>
    </div>
    <script>
        function display() {
            document.getElementById('w').textContent = window.innerWidth;
            document.getElementById('h').textContent = window.innerHeight;
            // alert("ขนาดหน้าต่างเปลี่ยนแล้ว!"); // อย่าใช้ alert ใน resize จริง
        }
        // เรียกครั้งแรก
        display();
    </script>
</body>
</html>

⚠️ คำเตือนประสิทธิภาพ (สำคัญมาก)

onresize ยิงบ่อยมากขณะปรับขนาด (หลายร้อยครั้ง/วินาที)

  • ❌ ไม่ควรทำงานหนัก (Complex calculations, DOM manipulation, API calls) โดยตรง
  • ❌ ไม่ควรใช้ alert(), console.log() บ่อย
  • ✅ ใช้ Debounce หรือ Throttle (แนะนำ 100-250ms)
  • ✅ ใช้ requestAnimationFrame สำหรับ Visual Updates
  • ✅ พิจารณา ResizeObserver สำหรับ Element-level resize (ทันสมัยกว่า)

ตัวอย่าง Debounce (แนะนำ)

function debounce(fn, delay) {
    let timeoutId;
    return function(...args) {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => fn.apply(this, args), delay);
    };
}

const handleResize = debounce(() => {
    console.log('Resize settled:', window.innerWidth, 'x', window.innerHeight);
    // ทำงานหนักที่นี่: recalculate layout, fetch data, etc.
    updateCharts();
    saveLayoutPreference();
}, 150);

window.addEventListener('resize', handleResize);

ResizeObserver (ทันสมัย แทน window.resize สำหรับ Element)

const observer = new ResizeObserver(entries => {
    for (let entry of entries) {
        console.log('Element resized:', entry.contentRect.width, 'x', entry.contentRect.height);
    }
});

observer.observe(document.querySelector('.my-component'));

การใช้งานทั่วไป

  • Responsive Layout Adjustment (Sidebar collapse, Grid reflow)
  • Canvas/WebGL Resize
  • Chart/Visualization Redraw
  • Sticky Header/Footer Position Recalculation
  • Font Size Scaling (Fluid Typography)