JavaScript擷取非行間樣式之currentStyle,getComputedStyle的使用

來源:互聯網
上載者:User

標籤:load   lang   asc   tco   com   back   script   樣式   get   

如果是行間樣式我們可以直接用style來擷取,但是如果是非行間樣式,則style不起作用了,這裡需要用到新的文法了。

1.currentStyle

 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Document</title> 6 <style type="text/css"> 7     #div1{width: 200px;height: 200px;background-color: red;}     8 </style> 9 <script type="text/javascript">10     window.onload=function(){11         var oDiv=document.getElementById("div1");12         alert(oDiv.currentStyle.width);  //在這裡應用currentStyle13     }14 </script>15 </head>16 <body>17 <div id="div1"></div>    18 </body>19 </html>

如上所示就是currentStyle的使用方法,跟style一樣,但是要注意的是,currentStyle僅相容IE。

currentStyle只能在IE使用,所以我們在其他瀏覽器還需要另外的方法擷取樣式。

 

2.getComputedStyle

我們將上面的彈出代碼換成

alert(getComputedStyle(oDiv,null).width);

就可以使這段代碼在Google,Firefox等瀏覽器上運行了。其中getComputedStyle的第二個參數,也就是null可以任意替換,不影響。值得注意的是,getComputedStyle在老版IE中也是不相容的。

為了在所有瀏覽器中都可以擷取樣式,可以作如下改動:

 1 window.onload=function(){ 2             var oDiv=document.getElementById("div1"); 3             //alert(getComputedStyle(oDiv,null).width); 4             if (oDiv.currentStyle) { 5                 alert(oDiv.currentStyle.width); 6             } 7             else{ 8                 alert(getComputedStyle(oDiv,null).width); 9             }10         }

 

 

  

 

JavaScript擷取非行間樣式之currentStyle,getComputedStyle的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.