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

Thuộc tính clientY của MouseEvent trong HTML DOM


Giới thiệu

Thuộc tính clientY của MouseEvent trong HTML DOM trả về tọa độ dọc (y) của con trỏ chuột tương đối với viewport (cửa sổ trình duyệt) khi một sự kiện chuột được kích hoạt. Kết hợp với clientX để lấy tọa độ ngang.

Cú pháp

Lấy giá trị clientY:

MouseEventObject.clientY

Ví dụ

Ví dụ game sử dụng clientX/clientY (tọa độ viewport).

<!DOCTYPE html> <html> <head> <title>MouseEvent clientY</title> <style> 
  * { padding: 2px; margin:5px; } 
  form { width:70%; margin: 0 auto; text-align: center; } 
  #outer { width:70%; margin: 0 auto; padding: 0; text-align: center; border:1px solid black; height: 105px; background-color: #28a745; } 
  input[type="button"] { border-radius: 10px; } 
  #upper { border-bottom: 1px solid black; height: 40px; margin: 0 0 15px 0; background-color: #DC3545; } 
  #lower { border-top: 1px solid black; height: 40px; margin: 15px 0 0 0; background-color: #DC3545; } 
</style> </head> <body> 
  <form> 
    <fieldset> 
      <legend>MouseEvent-clientY</legend> 
      <div id="outer"> 
        <div id="upper"><h2>Danger</h2></div> 
        <div id="lower"><h2>Danger</h2></div> 
      </div> 
      <input type="button" id="start" value="Start" onclick="gameStart()"> 
      <div id="divDisplay"></div> 
    </fieldset> 
  </form> 
  <script> 
    var divDisplay = document.getElementById('divDisplay'); 
    var gameDisplay = document.getElementById('outer'); 
    function playGame(event) { 
      var x = event.clientX; 
      var y = event.clientY; 
      if(y > 95 && y < 110){ 
        divDisplay.textContent = 'Keep Going!'; 
        if(x === 439){ 
          divDisplay.textContent = 'Congrats! You Did it!'; 
          gameDisplay.removeEventListener('mousemove', playGame); 
        } 
      } else { 
        divDisplay.textContent = 'You moved to DANGER area. You lose!'; 
        gameDisplay.removeEventListener('mousemove', playGame); 
      } 
    } 
    function gameStart(){ 
      gameDisplay.addEventListener('mousemove', playGame); 
    } 
  </script> </body> </html>

Kết quả

Sau khi nhấn Start và chuột ở vùng xanh:

Thuộc tính clientY của MouseEvent trong HTML DOM

Chuột ở cuối vùng xanh:

Thuộc tính clientY của MouseEvent trong HTML DOM

Chuột ở vùng đỏ:

Thuộc tính clientY của MouseEvent trong HTML DOM