JavaScript在IE和Firefox瀏覽器下的7個差異兼容寫法小結
2024-09-06 12:45:43
供稿:網友
在這篇文章中,作者介紹了7個JavaScript在IE和Firefox中存在的差異。
1. CSS “float” 值
訪問一個給定CSS 值的最基本句法是:object.style.property,使用駝峰寫法來替換有連接符的值,例如,訪問某個ID為”header”的<div>的 background-color值,我們使用如下句法:
document.getElementById("header").style.backgroundColor= "#ccc";
但由于”float“這個詞是一個JavaScript保留字,因此我們不能用 object.style.float來訪問,這里,我們可以在兩種瀏覽器中這么做:
在IE中這樣寫:
document.getElementById("header").style.styleFloat = "left";
在Firefox中這樣寫:
document.getElementById("header").style.cssFloat = "left";
2. 元素的推算樣式
JavaScript可以使用object.style.property句法,方便地在外部訪問和修改某個CSS樣式,但其限制是這些句法只能取出已設的行內樣式或者直接由JavaScript設定的樣式。并不能訪問某個外部的樣式表。為了訪問元素的”推算”樣式,我們可以使用下面的代碼:
在IE中這樣寫:
var myObject = document.getElementById("header");
var myStyle = myObject.currentStyle.backgroundColor;
在Firefox中這樣寫:
var myObject = document.getElementById("header");
var myComputedStyle = document.defaultView.getComputedStyle(myObject, null);
var myStyle = myComputedStyle.backgroundColor;
3. 訪問元素的”class”
像”float“一樣,”class“是JavaScript的一個保留字,在這兩個瀏覽器中我們使用如下句法來訪問”class”。
在IE中這樣寫:
var myObject = document.getElementById("header");
var myAttribute = myObject.getAttribute("className");
在Firefox中這樣寫:
var myObject = document.getElementById("header");
var myAttribute = myObject.getAttribute("class");
This syntax would also apply using the setAttribute method.
4. 訪問<label>標簽中的”for”
就第3點中所提到的,我們同樣需要使用不現的句法區分來訪問<label>標簽中的”for“:
在IE中這樣寫:
var myObject = document.getElementById("myLabel");
var myAttribute = myObject.getAttribute("htmlFor");
在Firefox中這樣寫:
var = document.getElementById("myLabel");
var myAttribute = myObject.getAttribute("for");
5. 獲取鼠標指針的位置
計算出鼠標指針的位置對你來說可能是非常少見的,不過當你需要的時候,在IE和Firefox中的句法是不同的。這里所寫出的代碼將是最最基本的,也可能是某個復雜事件處理中的某一個部分。但他們可以解釋其中的異同點。同時,必須指出的是結果相對于Firefox,IE會有更在的不同,這種方法本身就是有BUG的。通常,這種不同可以用”拖動位置”來得到補償,但,那是另外一個主題的文章了: ) !
在IE中這樣寫:
var myCursorPosition = [0, 0];