在許多需要互動的網頁場景中,實時掌握滑鼠的坐標位置十分有用。本文將介紹如何用 JavaScript 實時獲取滑鼠坐標值並顯示出來,其中涉及 JavaScript 操作滑鼠事件的相關技巧,頗具實用價值。
完整代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>JS實時獲取滑鼠坐標值並顯示</title>
</head>
<body>
<script type="text/javascript">
var getCoordInDocumentExample = function(){
var coords = document.getElementById("coords");
coords.onmousemove = function(e){
var pointer = getCoordInDocument(e);
var coord = document.getElementById("coord");
coord.innerHTML = "X,Y=(" + pointer.x + ", " + pointer.y + ")";
}
}
var getCoordInDocument = function(e) {
e = e || window.event;
var x = e.pageX || (e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft));
var y = e.pageY || (e.clientY + (document.documentElement.scrollTop || document.body.scrollTop));
return {'x':x,'y':y};
}
window.onload = function(){
getCoordInDocumentExample();
};
</script>
<div id="coords" style="width:500px;height:200px;background:#F2F1D7; border:2px solid #0066cc;">
請在此移動滑鼠。
</div>
<br />
<div id="coord" style="width:500px;border:2px solid #336699;">
</div>
</body>
</html>
關鍵在於 getCoordInDocument 函數:它優先使用 pageX/pageY 取得頁面坐標,若不存在則退回使用 clientX/clientY 加上滾動距離的計算方式,兼顧了不同瀏覽器的差異。而 getCoordInDocumentExample 則監聽指定區域的 onmousemove 事件,將實時坐標寫入顯示區域。