DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> javascript兼容多種浏覽器的一些寫法
javascript兼容多種浏覽器的一些寫法
編輯:關於JavaScript     
隨著以Firefox為代表的第三方浏覽器的興起,我們做的網站也不能再只面向IE了,如果把原來的一些Javascript代碼放到IE以外的浏覽器的話,往往都不能正常運行或出錯,所以這裡介紹一下怎麼改進我們的JS,讓它能更加規范,更加具有兼容性。

示例代碼:
<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 的寫法
以前訪問對象可能是:
document.all.apple 或者 apple
現在應該采用:
document.getElementById("apple") 以ID來訪問對象,且一個ID在頁面中必須是唯一的
document.getElementsByTagName("div")[0] 以標簽名來訪問對象
原來設置對象的屬性可能是:
document.all.apple.width=100 或 apple.width=100
現在應該采用:
document.getElementById("apple").setAttribute("width","100")
document.getElementsByTagName("div")[0].setAttribute("width","100")
訪問對象的屬性則采用:
document.getElementById("apple").getAttribute("width")
document.getElementsByTagName("div")[0].getAttribute("width")
W3C DOM在IE下的一些限制
因為起先的IE占據整個浏覽器95%的份額,沒有競爭壓力,所以這位老大就硬是要玩點另類,不完全按WEB標准來搞。

在IE下不能正確使用setAttribute來設置對象的style、class以及事件響應屬性,
因此我還得按原來的點記法來訪問和設置,以達到兼容各種浏覽器的效果,如:
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("我是香蕉")}
關於Firefox下的onload問題
function over(){
alert("頁面加載完畢")
}

正常情況下,我們賦與onload響應函數是:
document.body.onload= over
但是在Firefox下這樣無法執行,
所以我們都都采用下面這種形式:
window.onload=over
關於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);
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved