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

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

เหตุการณ์ onmousemove จะถูกกระตุ้นซ้ำๆ ตลอดเวลาที่เคอร์เซอร์เมาส์เคลื่อนที่อยู่ภายในพื้นที่ขององค์ประกอบ HTML นี้ ใช้สำหรับติดตามตำแหน่งเมาส์แบบเรียลไทม์

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

<!DOCTYPE html>
<html>
<body>
    <h3 id="myid" onmousemove="mouseMove()" style="padding: 20px; background: #f0f0f0; display: inline-block;">
        วางเมาส์ที่นี่และเคลื่อนที่
    </h3>
    <p>สีจะเปลี่ยนเป็นแดงขณะเคลื่อนที่เมาส์</p>
    <script>
        function mouseMove() {
            document.getElementById("myid").style.color = "red";
        }
    </script>
</body>
</html>

ตัวอย่างขั้นสูง: ติดตามพิกัดเมาส์

<div id="tracker" style="width: 400px; height: 200px; border: 1px solid #ccc; position: relative;">
    <span id="coords" style="position: absolute; top: 10px; left: 10px; background: rgba(0,0,0,0.7); color: white; padding: 5px 10px; border-radius: 3px;">X: 0, Y: 0</span>
</div>

<script>
    const tracker = document.getElementById('tracker');
    const coords = document.getElementById('coords');
    
    tracker.onmousemove = (e) => {
        // พิกัดสัมพัทธ์กับองค์ประกอบ
        const rect = tracker.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;
        coords.textContent = `X: ${Math.round(x)}, Y: ${Math.round(y)}`;
        coords.style.left = (x + 15) + 'px';
        coords.style.top = (y + 15) + 'px';
    };
    
    tracker.onmouseleave = () => {
        coords.textContent = 'X: -, Y: -';
    };
</script>

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

  • onmousemove ยิงบ่อยมาก (หลายร้อยครั้ง/วินาที) อาจทำให้ UI ลاگ
  • ใช้ Throttle หรือ Debounce สำหรับงานหนัก
  • หลีกเลี่ยง Layout/Reflow ใน Handler (เช่น ไม่ควรเปลี่ยน width/height บ่อย)
  • ใช้ requestAnimationFrame สำหรับ Animation

ตัวอย่าง Throttle

function throttle(fn, limit) {
    let inThrottle;
    return function(...args) {
        if (!inThrottle) {
            fn.apply(this, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    };
}

element.onmousemove = throttle((e) => {
    // ทำงานทุก 50ms สูงสุด
    heavyOperation(e);
}, 50);