通過 onmousemove 實時追蹤鼠標位置,onmouseout 清除顯示,構建座標提示交互。
<div id="coordiv" style="width:199px;height:99px;border:1px solid"
onmousemove="showCoords(event)" onmouseout="clearCoords()"></div>
<p id="demo"></p>
<script>
function showCoords(e) {
e = e || window.event; // IE 兼容
const x = e.clientX;
const y = e.clientY;
document.getElementById('demo').textContent = `座標: (${x}, ${y})`;
}
function clearCoords() {
document.getElementById('demo').textContent = '';
}
</script>
| 屬性 | 參考點 | 用途 |
|---|---|---|
| clientX/Y | 視口可視區左上角 | 最常用,相對瀏覽器窗口 |
| pageX/Y | 文檔左上角 (含滾動) | 頁面定位、絕對定位元素 |
| screenX/Y | 螢幕左上角 | 多螢幕、瀏覽器窗口位置 |
| offsetX/Y | 目標元素內部左上角 | 元素內部相對位置 |
| layerX/Y | 當前圖層左上角 | 非標準,Firefox/Chrome 支持 |
const area = document.getElementById('coordiv');
const output = document.getElementById('demo');
area.addEventListener('mousemove', e => {
output.textContent = `client: (${e.clientX}, ${e.clientY}) | page: (${e.pageX}, ${e.pageY})`;
});
area.addEventListener('mouseleave', () => {
output.textContent = '';
});
function throttle(fn, delay) {
let last = 0;
return (...args) => {
const now = Date.now();
if (now - last >= delay) {
last = now;
fn.apply(this, args);
}
};
}
area.addEventListener('mousemove', throttle(e => {
output.textContent = `(${e.clientX}, ${e.clientY})`;
}, 50)); // 50ms 節流,降低重繪壓力
掌握 5 種座標體系差異、現代 addEventListener 綁定、高頻事件節流優化,能構建流暢、精確的鼠標交互體驗。