原生js提取非行间样式

js用style属性可以获得html标签的样式,但是不能获取非行间样式,如何获取css的非行间样式呢,在低版本ie我们可以用currentStyle,在其他浏览器我们可以用getComputedStyle。

1、ie

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        #box{
            width:200px;
            height:200px;
            background: skyblue;
        }
    </style>
    <script>
        window.onload=function(){
            var box=document.getElementById("box");
            alert(box.currentStyle["width"]);       //200px
        }
    </script>
</head>
<body>
    <div id="box"></div>
</body>
</html>

2、其他浏览器

alert(getComputedStyle(box,false)["width"]);        //200px

3、兼容

<script>
        function getStyle(obj,attr){
            if(obj.currentStyle){
                return obj.currentStyle[attr];
            }else{
                return getComputedStyle(obj,false)[attr];
            }
        }

        window.onload=function(){
            var box=document.getElementById("box");
            alert(getStyle(box,"width"));    //兼容ie及其他浏览器
        } 
    </script>

4、获取及设置非行间样式

<script>
        function getStyle(obj,attr,value){
            if(arguments.length==2){         //根据参数个数执行相应操作
                if(obj.currentStyle){
                    return obj.currentStyle[attr];
                }else{
                    return getComputedStyle(obj,false)[attr];
                }
            }else{
                obj.style[attr]=value;         //这里需要注意,使用obj.style.attr无效
            }
            
        }

        window.onload=function(){
            var box=document.getElementById("box");
            getStyle(box,"backgroundColor","yellowgreen");          //把盒子的背景颜色设置成黄绿色
            alert(getStyle(box,"width"));      //弹出盒子的宽度200px
        } 
    </script>
原文地址:https://www.cnblogs.com/xlj-code/p/6427510.html