跨瀏覽器開發時,IE、Firefox、Opera 之間存在不少行為差異。以下整理幾個最常見的相容問題與解法。
直接寫 document.body.onload 在 IE 與 Opera 有效,但在 Firefox 中 document.body.onload 是 undefined,把函式賦值給 undefined 既不會生效也不會報錯。若要三者相容,建議直接用標準的事件綁定方式。
IE 使用 attachEvent,Firefox 使用 addEventListener,兩者寫法不同需分別處理。
漂浮廣告、對聯代碼在 XHTML 1.1 DTD 或 Firefox 下常失效。原因是依標準,瀏覽器的滾動條屬於 HTML 元素(即 document.documentElement),而非 body。解法是把 document.body.scrollTop 改為 document.documentElement.scrollTop。
在 IE 中,HTML 元素的 ID 可以直接當作變數名使用,但 Firefox 不允許:
<!-- 僅 IE 有效 -->
<input id="t1">
<input type="button" value="click me" onclick="alert(t1.value)">
<!-- 跨瀏覽器相容 -->
<input id="t1">
<input type="button" value="click me" onclick="alert(document.getElementById('t1').value)">
IE 在事件觸發時,有一個全域的 window.event 物件保存事件資訊:
<!-- IE Only --> <input type="button" onclick="alert(event.type)" onfocus="alert(event.type)">
Firefox 則把 event 物件作為第一個參數傳給事件處理函式:
<!-- Firefox Only --> <input type="button" onclick="alert(arguments[0].type)" onfocus="alert(arguments[0].type)">
實務上常見的折衷作法是:
<input value="click me" onclick="doEvent(arguments[0]);" />
在函式內部再統一判斷 window.event 是否存在,即可同時兼容兩種瀏覽器。