js中style,currentStyle和getComputedStyle的区别以及获取css操作方法(考虑兼容性和局限性)

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

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

遇到float这样的关键字属性,前面要加css ,float ==>cssFloat。

复合属性必须拆解,组合单词采用小驼峰写法。

写入的值必须是字符串。

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];

        console.log(getStyle(div,"background-color"));
        function getStyle(ele,attr){
            if(window.getComputedStyle){
            //火狐谷歌上兼容 return window.getComputedStyle(ele,null)[attr]; }
            //IE兼容 return ele.currentStyle[attr]; }
复制代码

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

原文地址:https://www.cnblogs.com/cui-ting/p/10625999.html