早期瀏覽器事件模型差異大,需同時處理 IE 與 Netscape 模式:
<body onMousemove="micro$oftMouseMove()">
<SCRIPT LANGUAGE="JavaScript">
if (navigator.appName == 'Netscape') {
document.captureEvents(Event.MOUSEMOVE);
document.onmousemove = netscapeMouseMove;
}
function netscapeMouseMove(e) {
if (e.screenX != document.test.x.value && e.screenY != document.test.y.value) {
document.test.x.value = e.screenX;
document.test.y.value = e.screenY;
}
}
function micro$oftMouseMove() {
if (window.event.x != document.test.x.value && window.event.y != document.test.y.value) {
document.test.x.value = window.event.x;
document.test.y.value = window.event.y;
}
}
</SCRIPT>
<FORM NAME="test">
X: <INPUT TYPE="TEXT" NAME="x" SIZE="4">
Y: <INPUT TYPE="TEXT" NAME="y" SIZE="4">
</FORM>
現代瀏覽器統一支援 event.clientX/Y (視窗座標) 與 event.pageX/Y (頁面座標):
document.addEventListener('mousemove', function(e) {
const x = e.clientX; // 視窗內水平座標
const y = e.clientY; // 視窗內垂直座標
// 或頁面座標(含捲軸)
// const x = e.pageX;
// const y = e.pageY;
console.log(`滑鼠座標: ${x}, ${y}`);
// 即時更新 UI
document.getElementById('coords').textContent = `X: ${x}, Y: ${y}`;
});
| 屬性 | 參考系 | 用途 |
|---|---|---|
| clientX/Y | 視窗可視區 | 定位浮層、Tooltip |
| pageX/Y | 整個文檔 | 拖曳、繪圖、熱力圖 |
| screenX/Y | 螢幕實體像素 | 多螢幕協同、全螢幕定位 |
| offsetX/Y | 目標元素內部 | Canvas 繪圖、圖片裁剪 |
requestAnimationFrame 節流高頻更新 UI。{passive: true} 提升捲動效能。掌握滑鼠座標獲取是前端互動開發的基石。現代專案建議採用標準事件模型,配合節流優化,即可流暢實現各類座標感知功能。