樣式表有三種方式
內(nèi)嵌樣式(inline Style) :是寫(xiě)在Tag里面的,內(nèi)嵌樣式只對(duì)所有的Tag有效壁查。
內(nèi)部樣式(internal Style Sheet):是寫(xiě)在HTML的里面的觉至,內(nèi)部樣式只對(duì)所在的網(wǎng)頁(yè)有效。
外部樣式表(External Style Sheet):如果很多網(wǎng)頁(yè)需要用到同樣的樣式(Styles)睡腿,將樣式(Styles)寫(xiě)在一個(gè)以.css為后綴的CSS文件里语御,然后在每個(gè)需要用到這些樣式(Styles)的網(wǎng)頁(yè)里引用這個(gè)CSS文件。 最常用的是style屬性嫉到,在JavaScript中沃暗,通過(guò)document.getElementById(id).style.XXX就可以獲取到XXX的值,但意外的是何恶,這樣做只能取到通過(guò)內(nèi)嵌方式設(shè)置的樣式值孽锥,即style屬性里面設(shè)置的值。
解決方案:引入currentStyle,runtimeStyle,getComputedStyle style 標(biāo)準(zhǔn)的樣式,可能是由style屬性指定的细层!
runtimeStyle 運(yùn)行時(shí)的樣式惜辑!如果與style的屬性重疊,將覆蓋style的屬性疫赎!
currentStyle 指 style 和 runtimeStyle 的結(jié)合盛撑! 通過(guò)currentStyle就可以獲取到通過(guò)內(nèi)聯(lián)或外部引用的CSS樣式的值了(僅限IE) 如:document.getElementById("test").currentStyle.top
要兼容FF,就得需要getComputedStyle 出馬了
注意: getComputedStyle是firefox中的捧搞, currentStyle是ie中的. 比如說(shuō)
<style>
#mydiv {
width : 300px;
}
</style>
var mydiv = document.getElementById('mydiv');
if(mydiv.currentStyle) {
var width = mydiv.currentStyle['width'];
alert('ie:' + width);
}else if(window.getComputedStyle) {
var width = window.getComputedStyle(mydiv , null)['width'];
alert('firefox:' + width);
}
總之抵卫,js獲取元素的樣式值,兼容多個(gè)瀏覽器時(shí)胎撇,可以按照如下來(lái)獲冉檎场:
如 ( element.currentStyle? element.currentStyle : window.getComputedStyle(element,null)).width
更詳細(xì)的介紹可參考
http://www.zhangxinxu.com/wordpress/2012/05/getcomputedstyle-js-getpropertyvalue-currentstyle/