DIV CSS 佈局教程網

各種瀏覽器相容問題整理
編輯:JavaScript基礎知識     

跨瀏覽器開發時,IE、Firefox、Opera 之間存在不少行為差異。以下整理幾個最常見的相容問題與解法。

一、用腳本設定 onload 事件

直接寫 document.body.onload 在 IE 與 Opera 有效,但在 Firefox 中 document.body.onload 是 undefined,把函式賦值給 undefined 既不會生效也不會報錯。若要三者相容,建議直接用標準的事件綁定方式。

二、綁定事件句柄

IE 使用 attachEvent,Firefox 使用 addEventListener,兩者寫法不同需分別處理。

三、浮動代碼與 documentElement/body

漂浮廣告、對聯代碼在 XHTML 1.1 DTD 或 Firefox 下常失效。原因是依標準,瀏覽器的滾動條屬於 HTML 元素(即 document.documentElement),而非 body。解法是把 document.body.scrollTop 改為 document.documentElement.scrollTop。

四、ID 與元素參照

在 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 是否存在,即可同時兼容兩種瀏覽器。

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