內(nèi)嵌樣式(inline Style) :是寫在Tag里面的,內(nèi)嵌樣式只對(duì)所有的Tag有效。
內(nèi)部樣式(internal Style Sheet):是寫在HTML的里面的,內(nèi)部樣式只對(duì)所在的網(wǎng)頁(yè)有效。
外部樣式表(External Style Sheet):如果很多網(wǎng)頁(yè)需要用到同樣的樣式(Styles),將樣式(Styles)寫在一個(gè)以.css為后綴的CSS文件里,然后在每個(gè)需要用到這些樣式(Styles)的網(wǎng)頁(yè)里引用這個(gè)CSS文件。 最常用的是style屬性,在JavaScript中,通過document.getElementById(id).style.XXX就可以獲取到XXX的值,但意外的是,這樣做只能取到通過內(nèi)嵌方式設(shè)置的樣式值,即style屬性里面設(shè)置的值。
解決方案:引入currentStyle,runtimeStyle,getComputedStyle style 標(biāo)準(zhǔn)的樣式,可能是由style屬性指定的!
runtimeStyle 運(yùn)行時(shí)的樣式!如果與style的屬性重疊,將覆蓋style的屬性!
currentStyle 指 style 和 runtimeStyle 的結(jié)合! 通過currentStyle就可以獲取到通過內(nèi)聯(lián)或外部引用的CSS樣式的值了(僅限IE) 如:document.getElementById("test").currentStyle.top
要兼容FF,就得需要getComputedStyle 出馬了
注意: getComputedStyle是firefox中的, currentStyle是ie中的.
大家都知道,用document.getElementById(‘element').style.xxx可以獲取元素的樣式信息,可是它獲取的只是DOM元素style屬性里的樣式規(guī)則,對(duì)于通過class屬性引用的外部樣式表,就拿不到我們要的信息了。
DOM標(biāo)準(zhǔn)里有個(gè)全局方法getComputedStyle,可以獲取到當(dāng)前對(duì)象樣式規(guī)則信息,如:getComputedStyle(obj,null).paddingLeft,就能獲取到對(duì)象的左內(nèi)邊距。但是事情還沒完,萬(wàn)惡的IE不支持此方法,它有自己的一個(gè)實(shí)現(xiàn)方式,那就是currentStyle,不同于全局方法getComputedStyle,它是作為DOM元素屬性存在的,如:obj.currentStyle.paddingLeft,在IE中就獲取到對(duì)象的左內(nèi)邊距了,兼容性的寫法如下:
return window.getComputedStyle ? window.getComputedStyle(obj,null).paddingLeft : obj.currentStyle.paddingLeft;
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>js用currentStyle和getComputedStyle獲取css樣式</title> <style type="text/css"> #div1{width:100px; height:100px; background:red;} </style> <script type="text/javascript"> function getStyle(obj, attr) { if(obj.currentStyle) { return obj.currentStyle[attr]; } else { return getComputedStyle(obj,false)[attr]; } } window.onload=function() { var oDiv=document.getElementById('div1'); alert(getStyle(oDiv,'width')) } </script> </head> <body> <div id="div1"></div> </body> </html>
如對(duì)本文有疑問,請(qǐng)?zhí)峤坏浇涣髡搲瑥V大熱心網(wǎng)友會(huì)為你解答??! 點(diǎn)擊進(jìn)入論壇