樣式表有三種方式
內嵌樣式(inline Style) :是寫在Tag裡面的,內嵌樣式只對所有的Tag有效。
內部樣式(internal Style Sheet):是寫在HTML的<head></head>裡面的,內部樣式只對所在的網頁有效。
外部樣式表(External Style Sheet):如果很多網頁需要用到同樣的樣式(Styles),將樣式(Styles)寫在一個以.css為尾碼的CSS檔案裡,然後在每個需要用到這些樣式(Styles)的網頁裡引用這個CSS檔案。
下面的是讀取除了內嵌樣式之外樣式的js,只能讀不能寫。
複製代碼 代碼如下:
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);
}
另外在FF下還可以通過下面的方式擷取
document.defaultView.getComputedStyle(mydiv,null).width
window.getComputedStyle(mydiv , null).width
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>Document</title> <style> #test{width:200px;} </style> <script> </script> </head> <body> <div id="test">this is test content</div> <script type="text/javascript"> var oTest = document.getElementById('test'); oTest.style.width = 400+'px'; if(oTest.currentStyle){ alert('ie: ' + oTest.currentStyle['width']); } else { alert('ff: ' + window.getComputedStyle(oTest, null)['width']); } </script> </body> </html>
[Ctrl+A 全選 注:如需引入外部Js需重新整理才能執行]
最常用的是style屬性,在JavaScript中,通過document.getElementById(id).style.XXX就可以擷取到XXX的值,但意外的是,這樣做只能取到通過內嵌方式設定的樣式值,即style屬性裡面設定的值。
解決方案:引入currentStyle,runtimeStyle,getComputedStyle
style 標準的樣式!可能是由style屬性指定的!
runtimeStyle 運行時的樣式!如果與style的屬性重疊,將覆蓋style的屬性!
currentStyle 指 style 和 runtimeStyle 的結合!
通過currentStyle就可以擷取到通過內聯或外部參考的CSS樣式的值了(僅限IE)
如:document.getElementById("test").currentStyle.top
要相容FF,就得需要getComputedStyle 出馬了
注意:getComputedStyle是firefox中的,
currentStyle是ie中的.
比如說
複製代碼 代碼如下:
<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);
}
另外在FF下還可以通過下面的方式擷取
複製代碼 代碼如下:
document.defaultView.getComputedStyle(mydiv,null).width
window.getComputedStyle(mydiv , null).width