製作拖拽、繪圖或交互效果時,實時掌握鼠標位置是常見需求。本文用一個簡潔的例子,演示如何借助 onmousemove 與 onmouseout 事件獲取並顯示鼠標坐標。
當鼠標在指定區域內移動時,頁面會動態顯示當前坐標;移出區域後坐標信息清空。
<!DOCTYPE html> <html> <head> <script> function myFunction(e) { x=e.clientX; y=e.clientY; coor="Coordinates: (" + x + "," + y + ")"; document.getElementById("demo").innerHTML=coor } function clearCoor() { document.getElementById("demo").innerHTML=""; } </script> </head> <body style="margin:0px;"> <div id="coordiv" style="width:199px;height:99px;border:1px solid" onmousemove="myFunction(event)" onmouseout="clearCoor()"></div> <p>Mouse over the rectangle above, and get the coordinates of your mouse pointer.</p> <p id="demo"></p> </body> </html>
關鍵在於事件對象的 clientX 與 clientY 屬性,它們分別給出鼠標相對於視口的橫縱坐標。掌握這兩個屬性,你就能輕鬆實現各類跟隨鼠標的交互效果。