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

Thuộc tính sự kiện onmousemove trong HTML

Thuộc tính sự kiện onmousemove kích hoạt khi con trỏ chuột di chuyển bên trong vùng của một phần tử HTML (liên tục khi di chuyển).

Cú pháp

<tagname onmousemove="script"></tagname>

Ví dụ

<!DOCTYPE html>
<html>
<head>
<style>
  body { color: #000; height: 100vh; background-color: #FBAB7E; background-image: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%); text-align: center; }
  .circle { background: #db133a; height: 150px; width: 150px; border-radius: 50%; margin: 10px auto; transition: background 0.3s; }
  p { margin: 30px auto; }
</style>
</head>
<body>
<h1>Demo onmousemove</h1>
<div class="circle" onmousemove="mouseMove()" onmouseout="mouseOut()"></div>
<p>Di chuyển chuột trên vòng tròn đỏ</p>
<script>
  function mouseMove() {
    document.querySelector('.circle').style.background = '#2274A5';
  }
  function mouseOut() {
    document.querySelector('.circle').style.background = '#0B6E4F';
  }
</script>
</body>
</html>

Kết quả

Di chuyển chuột trên vòng tròn → liên tục kích hoạt, giữ màu xanh dương. Rời khỏi → xanh lá.

Lưu ý: Sự kiện này kích hoạt rất nhiều lần (mỗi pixel di chuyển). Tránh xử lý nặng trong handler. Dùng throttle/debounce nếu cần tính toán phức tạp (vd: vẽ canvas, drag).