JS获取CSS属性值

JS获取CSS属性值方法有很多,我这里介绍两种

obj.style方法,这个方法只能JS只能获取写在html标签中的写在style属性中的值(style="..."),看一下代码

 

XML/HTML代码
  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.   
  13. <body>  
  14. <div id="css88" class="ss" style="width:200px; height:200px; background:#333333">JS获取CSS属性值</div>  
  15. <script type="text/javascript">  
  16.     alert(document.getElementById("css88").style.width);//200px   
  17.     alert(document.getElementById("css88").style.color);//空白   
  18. </script>      
  19. </body>  
  20. </html>  

上面这个例子对id为"css88"的div设置了2种烦事的样式,包括style和外部样式class。

从alert出来的信息可以看到,document.getElementById("css88").style方法获取不到class为ss的属性和值。

那么这么样才能获取到class为ss的属性和值呢?

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

网上一个比较方法是:

 

XML/HTML代码
  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.   
  7. <style type="text/css">  
  8. <!--  
  9. .ss{background:blue; color:#cdcdcd; width:200px}  
  10. -->  
  11. </style>  
  12. </head>  
  13.   
  14. <body>  
  15. <p id="qq" class="ss" >sdf</p>  
  16.   
  17. <script type="text/javascript">  
  18. function GetCurrentStyle (obj, prop) {     
  19.     if (obj.currentStyle) {        
  20.         return obj.currentStyle[prop];     
  21.     }      
  22.     else if (window.getComputedStyle) {        
  23.         propprop = prop.replace (/([A-Z])/g, "-$1");           
  24.         propprop = prop.toLowerCase ();        
  25.         return document.defaultView.getComputedStyle (obj,null)[prop];     
  26.     }      
  27.     return null;   
  28. }   
  29. var dd=document.getElementById("qq");   
  30. alert(GetCurrentStyle(dd,"width"));   
  31. </script>  
  32. </body>  
  33. </html>  

当然,如果您是引用外部的css文件同样适用。

另:可以将上面的方法简化为

JavaScript代码
  1. function getDefaultStyle(obj,attribute){ // 返回最终样式函数,兼容IE和DOM,设置参数:元素对象、样式特性   
  2.  return obj.currentStyle?obj.currentStyle[attribute]:document.defaultView.getComputedStyle(obj,false)[attribute];   

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值