javascript 讀取內聯之外的樣式(style、currentStyle、getComputedStyle區別介紹)_javascript技巧

來源:互聯網
上載者:User

樣式表有三種方式
內嵌樣式(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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.