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

เหตุการณ์ onscroll: รันสคริปตเมื่อเลื่อนสกอรลล์บาร์ขององค์ประกอบ

เหตุการณ์ onscroll จะถูกกระตุ้นเมื่อผู้ใช้เลื่อนเนื้อหาภายในองค์ประกอบที่มี Scrollbar (มี overflow: scroll หรือ auto) รวมถึง window (หน้าต่างทั้งหมด)

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

<!DOCTYPE html>
<html>
<head>
    <style>
        #myid {
            width: 250px;
            height: 80px;
            border: 2px solid blue;
            overflow: scroll;
            padding: 10px;
        }
    </style>
</head>
<body>
    <p>เลื่อนกล่องด้านล่าง</p>
    <div id="myid" onscroll="display()">
        นี่คือข้อความตัวอย่างที่ยาวพอให้มีสกอรลล์บาร์
        <br><br><br><br><br><br><br><br><br><br>
        สิ้นสุดข้อความ
    </div>
    <script>
        function display() {
            const el = document.getElementById("myid");
            el.style.color = "blue";
            // console.log('Scroll position:', el.scrollTop, el.scrollLeft);
        }
    </script>
</body>
</html>

คุณสมบัติ Scroll ที่มีประโยชน์

คุณสมบัติ คำอธิบาย
scrollTop พิกเซลที่เลื่อนลงจากด้านบน
scrollLeft พิกเซลที่เลื่อนขวาจากด้านซ้าย
scrollHeight ความสูงรวมของเนื้อหา (รวมส่วนที่ซ่อน)
scrollWidth ความกว้างรวมของเนื้อหา
clientHeight ความสูงส่วนที่มองเห็น (Viewport)
clientWidth ความกว้างส่วนที่มองเห็น

⚠️ ประสิทธิภาพ: ใช้ Passive Listener + Throttle

// แบบ Modern: Passive + Throttle
function throttle(fn, limit) {
    let inThrottle;
    return function(...args) {
        if (!inThrottle) {
            fn.apply(this, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    };
}

const handleScroll = throttle(() => {
    const scrolled = window.scrollY;
    const maxScroll = document.body.scrollHeight - window.innerHeight;
    const progress = (scrolled / maxScroll) * 100;
    
    // อัปเดต Progress Bar
    document.getElementById('progress').style.width = progress + '%';
    
    // Lazy Load Images
    // Check element visibility
}, 100); // 100ms = 10fps

// Passive listener ไม่บล็อก Scroll
window.addEventListener('scroll', handleScroll, { passive: true });

การประยุกต์ใช้ทั่วไป

  • Infinite Scroll / Lazy Loading
  • Sticky Header/Navbar (Hide/Show on scroll)
  • Scroll Progress Indicator
  • Parallax Effects
  • Back to Top Button (Show after scroll down)
  • Scroll Spy (Active Nav Link by Section)

Intersection Observer (ทางเลือกทันสมัย)

สำหรับตรวจจับ Element เข้า/ออก Viewport ใช้ IntersectionObserver แทน Scroll Event - ประสิทธิภาพดีกว่ามาก