上篇文章講到如何設(shè)置元素樣式,本文將繼續(xù)給大家分享如何獲取元素樣式。
一、style,只獲取標(biāo)簽上定義的行內(nèi)樣式
在這里講的style用法包括三個(gè):style、style.cssText和style.getPropertyValue(),直接看個(gè)例子吧:
/*CSS*/
#box{ width: 200px; height: 200px; background-color: #0f0;}
<!--HTML-->
<div id="box" style="width: 100px; background-color: #f00;"></div>
//JavaScript
var box = document.getElementById("box");
console.log(box.style.cssText); // "width: 100px; background-color: rgb(255, 0, 0);"
console.log(box.style.width); // "100px"
console.log(box.style.height); // ""
console.log(box.style.getPropertyValue('background-color')); // "rgb(255, 0, 0)"
通過(guò)上面例子我們可以看出,通過(guò)這種方式只能獲取行內(nèi)樣式,并不能獲取到CSS樣式表中的樣式。
二、cssRules,只獲取CSS樣式表中定義的樣式
接著上面的例子:
//JavaScript
var sheet = document.styleSheets[0]; // 獲取頁(yè)面中第一個(gè)樣式表
var rules = sheet.cssRules; // 獲取頁(yè)面中第一個(gè)樣式表中定義的所有規(guī)則,rules[0]即代表第一條規(guī)則
console.log(rules[0].style.cssText); // "width: 200px; height: 200px; background-color: rgb(0, 255, 0);"
console.log(rules[0].style.width); // "200px"
console.log(rules[0].style.height); // "200px"
console.log(rules[0].style.getPropertyValue('background-color')); // "rgb(0, 255, 0)"
可以看出,用法其實(shí)與上面類似,只不過(guò)是主體變?yōu)閞ules[0]而不是box,所以只能獲取到樣式表中的樣式,而并不能獲取到行內(nèi)樣式。
三、getComputedStyle(),獲取當(dāng)前元素的計(jì)算樣式
以上兩種方式,都具有太強(qiáng)的針對(duì)性,不夠靈活,因?yàn)楂@取到的樣式可能并不是當(dāng)前元素最終表現(xiàn)出來(lái)的樣式。因此,如果想要獲取所有樣式表層疊而來(lái)的當(dāng)前元素的樣式,我們就要用到getComputedStyle()方法。
依然繼續(xù)前面的例子:
console.log(getComputedStyle(box).cssText); // 注意不僅僅只打印現(xiàn)有樣式簡(jiǎn)單的疊加覆蓋結(jié)果,而是還會(huì)有很多其他樣式
console.log(getComputedStyle(box).width); // "100px"
console.log(getComputedStyle(box).height); // "200px"
console.log(getComputedStyle(box).getPropertyValue('background-color')); // "rgb(255, 0, 0)"
很明顯,用法還是和style類似,但是通常情況下使用這種方式獲取到的樣式才是我們真正所需要的。
兼容性:在IE8下,getPropertyValue()、cssRules和getComputedStyle()統(tǒng)統(tǒng)都不兼容,可以分別使用style.[屬性名]、rules和currentStyle的方式替代,具體用法本文將不再說(shuō)明,在此也希望其他開(kāi)發(fā)者放棄兼容IE8及更早版本,如今2017都快接近尾聲,微軟自己都早已放棄,我們何必繼續(xù)再慣著那部分少量用戶而折磨自己呢?