js中style,currentStyle和getComputedStyle的区别以及获取css操作方法

在js中,之前我们获取属性大多用的都是ele.style.border这种形式的方法,但是这种方法是有局限性的,该方法只能获取到行内样式,获取不了外部的样式.所以呢下面我就教大家获取外部样式的方法,因为获取外部的样式存在兼容性的问题,所以后面我还会教大家解决兼容性的方法.

style:各大浏览器都兼容,能设置样式和获取样式,但是获取不了外部样式,如果写了行内没有的样式,返回的是空值

写法:ele.style.attr(这样为获取),ele.style.attr="值";

currentStyle属性和getComputedStyle属性不能设置属性,只能获取

currentStyle:该属性只兼容IE,不兼容火狐和谷歌

 写法:ele.currentStyle["attr"]或者ele.currentStyle.attr;

getComputedStyle:该属性是兼容火狐谷歌,不兼容IE

写法:window.getComputedStyle(ele,null)[attr]获取是window.getComputedStyle(ele,null).attr

下面我就贴上我的代码:

复制代码
var div=document.getElementsByTagName("div")[0];
        if(div.currentStyle){
            //IE上兼容
            console.log(div.currentStyle["width"]);
        }
        else{
            //火狐谷歌上兼容
            console.log(window.getComputedStyle(div,null)["width"]);
        }
复制代码

下面呢,我写了一个兼容性的方法,大家可以参考参考:

复制代码
        var div=document.getElementsByTagName("div")[0];

        console.log(getStyle(div,"background-color"));
        function getStyle(ele,attr){
            if(window.getComputedStyle){
                return window.getComputedStyle(ele,null)[attr];
            }
            return ele.currentStyle[attr];
        }
复制代码

说明:在IE中获取到的颜色是16进制的,在火狐谷歌中获取的颜色是rgb模式的

原文地址:https://www.cnblogs.com/gxywb/p/10208256.html