JS获取css属性

来源:互联网 发布:单页淘宝客网站源码 编辑:程序博客网 时间:2024/05/22 13:30

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. }
原创粉丝点击