欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

js获取行间样式和当前样式的代码

程序员文章站 2022-04-30 15:58:23
...
本篇文章给大家带来的内容是关于js获取行间样式和当前样式的代码,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

获取行间样式style

<!DOCTYPE html>
<html>
<head>
  <title>获取行间样式</title>
  <script>
    window.onload=function(){
      op=document.getElementById("p1");
      alert(op.style.width);
    }
  </script>
</head>
<body>
  <p id="p1" style="width:100px; height:100px; background:#f00;"></p>
</body>
</html>

获取元素的当前样式currentStyle(ie)和getComputedStyle(非ie) 兼容方法

<!DOCTYPE html>
<html>
<head>
  <title>获取样式兼容写法</title>
  <script>
    function getStyle(obj,name){
      if(obj.currentStyle){
        return obj.currentStyle[name];
      }else{
        return getComputedStyle(obj)[name];
      }
    }
    window.onload=function(){
      op=document.getElementById("p1");
      // alert(getStyle(op,"width"));
      alert(getStyle(op,"background"));
      // alert(getStyle(op,"backgroundColor"))
    }
  </script>
</head>
<body>
  <p id="p1" style="width:100px; height:100px; background:#f00;"></p>
</body>
</html>

运行结果:
js获取行间样式和当前样式的代码
从上面代码的运行结果我们可以看出来background返回的并不是#f00而是一个复合样式,所以遇见像background等复合样式的时候要特殊处理,在这里可以用backgroundColor。

  • 复合样式 background、border...

  • 单一样式 width、height、position

相关推荐:

js中RegExp对象是什么?js中RegExp对象的详细介绍

js正则表达式的test()、exec()以及match()之间的区别对比(附示例)

以上就是js获取行间样式和当前样式的代码的详细内容,更多请关注其它相关文章!

相关标签: javascript