JS 獲取 html元素的樣式有三種方式:style、getComputedStyle 和 currentStyle等。區(qū)別在于:
(1)style 只能獲取行間樣式,但能設(shè)置樣式。
(2)getComputedStyle 和 currentStyle 能夠獲取 行間樣式/非行間樣式/瀏覽器默認樣式,但存在瀏覽器兼容問題,且不能設(shè)置樣式。
一、element.style 獲取行間樣式,以及設(shè)置樣式
<title>Javascript</title> #box{width: 100px;height: 100px;margin-left: 100px;} <div id="box" style="background-color:#ccc;margin-top:100px;"></div> window.onload = function(){ var oBox = document.getElementById('box'); console.log(oBox.style.width); //結(jié)果為:100px console.log(oBox.style.background); //結(jié)果:rgb(204,204,204),但ie下為空 console.log(oBox.style.backgroundColor); //結(jié)果:rgb(204,204,204)或#ccc console.log(oBox.style.margin); //結(jié)果為空 console.log(oBox.style.marginTop); //結(jié)果:100px oBox.style.height = '120px'; //設(shè)置樣式
style總結(jié):
(1)對于復(fù)合屬性(如background),假設(shè)行間設(shè)置了樣式:background-color:#333,不能通過 element.style.background 來獲?。ㄒ娚厦胬樱?/p>
(2)css屬性使用駝峰法,如 backgroundColor、marginTop等。
(3)不同瀏覽器,一些 css 屬性值可能會發(fā)生轉(zhuǎn)換,如例子中的 background-color,標準瀏覽器會轉(zhuǎn)換為 rgb 形式。
二、getComputedStyle 獲取css屬性值
<title>Javascript</title> #box{width: 100px;height: 100px;margin-left: 100px;} <div id="box" style="background-color:#ccc;margin-top:100px;"></div> window.onload = function(){ var oBox = document.getElementById('box'); var a = getComputedStyle(oBox, null)['width']; // 100px var b = getComputedStyle(oBox, null).getPropertyValue('backgroundColor'); //chrome為null, ie為空 var c = getComputedStyle(oBox, null)['backgroundColor'];// rgb(204,204,204) var d = getComputedStyle(oBox,null)['padding'];// chrome為0px, ie為空
getComputedStyle總結(jié):
(1)標準瀏覽器,ie9+以上支持 getComputedStyle。
(2)對于復(fù)合屬性:使用 getPropertyValue 獲取屬性值時,不能使用駝峰寫法,如:例子中的 getpropertyValue('backgroundColor') 無法正確獲得值,而必須寫成 background-color。
(3)另外,以下寫法也正確:getComputedStyle(oBox, null)['backgroundColor']、getComputedStyle(oBox, null)['background-color'], 以及 getComputedStyle(oBox, null).backgroundColor 等。
(4)當沒有設(shè)置某個屬性值時,chrome 會讀取瀏覽器該屬性的默認值,而 ie9+ 下結(jié)果為空。如例子中的 padding。
(5)getComputedStyle 第二個參數(shù)為”偽類“,一般用不著,設(shè)置為 null 即可。
三、IE 下 currentStyle 獲取css 屬性值
還是上面的例子:
window.onload = function(){ var oBox = document.getElementById('box'); var a = oBox.currentStyle['width']; // 100px var b = oBox.currentStyle['background-color']; // #ccc var c = oBox.currentStyle['backgroundColor']; // #ccc var d = oBox.currentStyle.backgroundColor; // #ccc //var e = oBox.currentStyle.background-color; 錯誤 var e = oBox.currentStyle['padding']; // 0px console.log(a, b, c, d, e);
currentStyle 總結(jié):
(1)只在 IE 下支持(網(wǎng)上 opera 也支持,但未測)。
(2)注意 ['backgroundColor']、['background-color'] 和 .backgroundColor 等寫法。
(3)未設(shè)置的屬性值,currentStyle 會讀取瀏覽器默認值,如例子中的 padding。
四、不同瀏覽器下,獲取 css 屬性值 的兼容寫法
function getStyle(oElement, sName){ return oElement.currentStyle ? oElement.currentStyle[sName] : getComputedStyle(oElement, null)[sName];
|