取得滑鼠事件物件是前端最早的跨瀏覽器陷阱之一。
window.event 物件,不需要參數也能取得事件。window.event,事件物件必須透過函式參數傳入。把 event 當成參數傳進函式,再用「或」運算子做兼容:
<input type="button" onmousemove="showDiv(event);">
<script>
function showDiv(event) {
var e = window.event || event; // IE 走 window.event,Firefox 走傳入參數
e.clientX; // 滑鼠的 X 座標
e.clientY; // 滑鼠的 Y 座標
}
</script>
注意 onmousemove="showDiv(event)" 中的 event 不要加引號,加上引號會被當成字串而非事件物件。
只要一律把 event 當參數傳入,再用 window.event || event 做一次取值,就能同時滿足兩邊。這個模式也適用於 keydown、mouseover 等其他事件,值得當成固定寫法記起來。