DIV CSS 佈局教程網

window.event 在 IE 與 Firefox 的差異與解法
編輯:關於JavaScript     

取得滑鼠事件物件是前端最早的跨瀏覽器陷阱之一。

差異所在

  • IE:提供全域的 window.event 物件,不需要參數也能取得事件。
  • Firefox:沒有 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 等其他事件,值得當成固定寫法記起來。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved