JS獲取css屬性

obj.style方法,這個方法只能JS只能獲取寫在html標籤中的寫在style屬性中的值(style="..."),看一下代碼

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5. <title>JS獲取CSS屬性值</title>
  6. <style type="text/css">
  7. <!--
  8. .ss{color:#cdcdcd;}
  9. -->
  10. </style>
  11. </head>
  12. <body>
  13. <div id="css88" class="ss" style="width:200px; height:200px; background:#333333">JS獲取CSS屬性值</div>
  14. <script type="text/javascript">
  15. alert(document.getElementById("css88").style.width);//200px
  16. alert(document.getElementById("css88").style.color);//空白
  17. </script>
  18. </body>
  19. </html>

上面這個例子對id爲"css88"的div設置了2種煩事的樣式,包括style和外部樣式class。

從alert出來的信息可以看到,document.getElementById("css88").style方法獲取不到class爲ss的屬性和值。

那麼這麼樣才能獲取到class爲ss的屬性和值呢?

IE中使用的是obj.currentStyle方法,而FF是用的是getComputedStyle 方法。

網上一個比較方法是:

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  5. <title>S獲取CSS屬性值</title>

  6. <style type="text/css">
  7. <!--
  8. .ss{background:blue; color:#cdcdcd; width:200px}
  9. -->
  10. </style>
  11. </head>

  12. <body>
  13. <p id="qq" class="ss" >sdf</p>

  14. <script type="text/javascript">
  15. function GetCurrentStyle (obj, prop) {
  16. if (obj.currentStyle) {
  17. return obj.currentStyle[prop];
  18. }
  19. else if (window.getComputedStyle) {
  20. propprop = prop.replace (/([A-Z])/g, "-$1");
  21. propprop = prop.toLowerCase ();
  22. return document.defaultView.getComputedStyle (obj,null)[prop];
  23. }
  24. return null;
  25. }
  26. var dd=document.getElementById("qq");
  27. alert(GetCurrentStyle(dd,"width"));
  28. </script>
  29. </body>
  30. </html>

當然,如果您是引用外部的css文件同樣適用。

另:可以將上面的方法簡化爲

  1. function getDefaultStyle(obj,attribute){ // 返回最終樣式函數,兼容IE和DOM,設置參數:元素對象、樣式特性
  2. return obj.currentStyle?obj.currentStyle[attribute]:document.defaultView.getComputedStyle(obj,false)[attribute];
  3. }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章