下面一段代码:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <style type="text/css">
            #box{
                height: 200px;
                width: 200px;
            }
        </style>
    </head>
    <body>
        <div >            
        </div>
    </body>
</html>

通过下面这种方式去获取元素的CSS样式

var oBox = document.getElementById("box");
console.log(oBox.style.backgroundColor);
console.log(oBox.style.height);

只能获取到行内样式"background-color: red;"的值,获取不到height: 200px;的值。

需要获取计算后的样式可以采用下面这种方法

var oBox = document.getElementById("box");
console.log(getComputedStyle(oBox).height);

getComputedStyle方法只有标准浏览器才支持,像IE8以下的低版本浏览器不支持,低版本浏览器只支持oBox.currentStyle.height

封装一个函数,兼容不同版本浏览器:

function getStyle(obj,attr){
    if(window.getComputedStyle){
     return window.getComputedStyle(obj)[attr];
    }
    else{
     return obj.currentStyle[attr];
    }
}

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-04-27
  • 2022-02-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-04-05
  • 2021-12-09
  • 2022-03-03
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-26
相关资源
相似解决方案