Believe in yourself.

Javascript学习笔记、获取元素CSS样式

下面一段代码:

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

通过下面这种方式去获取元素id="box"的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];
    }
}

 

posted @ 2020-11-25 15:38  eastonliu  阅读(236)  评论(0编辑  收藏  举报