隨著以Firefox為代表的第三方瀏覽器的興起,我們做的網(wǎng)站也不能再JUST?IE了,如果把原來的一些Javascript代碼放到IE以外的瀏覽器的話,往往都不能正常運(yùn)行或出錯(cuò),所以這里介紹一下怎么改進(jìn)我們的JS,讓它能更加規(guī)范,更加具有兼容性。
示例代碼:
<body><table?border="1"?cellspacing="0"?cellpadding="0"?id="apple"?>?<tbody>
??<tr>?????<td?id="banana"?style="color:red"?>不吃蘋果</td>??</tr>
?</tbody></table></body>
盡量采用W3C?DOM?的寫法
以前訪問對(duì)象可能是:
document.all.apple?或者?apple
現(xiàn)在應(yīng)該采用:
document.getElementById("apple")?以ID來訪問對(duì)象,且一個(gè)ID在頁面中必須是唯一的
document.getElementsByTagName("div")[0]?以標(biāo)簽名來訪問對(duì)象
原來設(shè)置對(duì)象的屬性可能是:
document.all.apple.width=100?或?apple.width=100
現(xiàn)在應(yīng)該采用:
document.getElementById("apple").setAttribute("width","100")
document.getElementsByTagName("div")[0].setAttribute("width","100")
訪問對(duì)象的屬性則采用:
document.getElementById("apple").getAttribute("width")
document.getElementsByTagName("div")[0].getAttribute("width")
W3C?DOM在IE下的一些限制
因?yàn)槠鹣鹊腎E占據(jù)整個(gè)瀏覽器95%的份額,沒有競(jìng)爭(zhēng)壓力,所以這位老大就硬是要玩點(diǎn)另類,不完全按WEB標(biāo)準(zhǔn)來搞。
在IE下不能正確使用setAttribute來設(shè)置對(duì)象的style、class以及事件響應(yīng)屬性,
因此我還得按原來的點(diǎn)記法來訪問和設(shè)置,以達(dá)到兼容各種瀏覽器的效果,如:
document.getElementById("banana").class
document.getElementById("banana").style.color
document.getElementById("banana").onclick
document.getElementById("banana").class="fruit"
document.getElementById("banana").style.color="blue"
document.getElementById("banana").onclick=?function?(){alert("我是香蕉")}
關(guān)于Firefox下的onload問題
function?over(){
?alert("頁面加載完畢")
}
正常情況下,我們賦與onload響應(yīng)函數(shù)是:
document.body.onload=?over
但是在Firefox下這樣無法執(zhí)行,
所以我們都都采用下面這種形式:
window.onload=over
關(guān)于IE下TABLE無法插入新行的問題
IE下TABLE無論是用innerHTML還是appendChild插入<tr>都沒有效果,而其他瀏覽器卻顯示正常。解決他的方法是,將<tr>加到TABLE的<tbody>元素中,如下面所示:
var?row?=?document.createElement("tr");
var?cell?=?document.createElement("td");
var?cell_text?=?document.createTextNode("香蕉不吃蘋果");
cell.appendChild(cell_text);
row.appendChild(cell);
document.getElementsByTagName("tbody")[0].appendChild(row);