js-style,currentStyle与getComputedStyle()

来源:互联网 发布:o2o网络借贷模式的特点 编辑:程序博客网 时间:2024/05/22 12:24

一,区别

style专指行间样式,即标签带style属性,例如:

 <script>        window.onload=function(){            var oDiv=document.getElementById("div1");            //alert("行间样式测试:"+oDiv.style.backgroundColor);              }    </script><div id="div1" style="width: 200px;height: 100px;background: red">    这是行间样式的测试</div>

currentStyle指全局样式表、内嵌样式和 HTML 标签属性中指定的对象格式和样式的所有样式,例如以下行间和非行间样式都为currentStyle范围:

<html><head lang="en">    <style>        /*非行间样式*/        #div1            border:1px solid #ccc;        }    </style>     <script>        window.onload=function(){            var oDiv=document.getElementById("div1");            //currentStyle能取行间和非行间样式            alert("测试:"+oDiv.currentStyle.backgroundColor+"---"+oDiv.currentStyle.border)        }    </script>    </head><body><div id="div1" style="width: 200px;height: 100px;background: red">    本div中指定的style中样式为行间样式</div>

但是currentStyle谷歌和火狐浏览器可能不兼容。解决办法是:使用
getComputedStyle()。
Dom中getComputedStyle方法可用来获取元素中所有可用的css属性列表,以数组形式返回,并且是readonly的。IE中则用currentStyle代替。
语法:arr_style=window.getComputedStyle(elem_id,ov)
其中ov:伪元素,是否要获取伪元素属性值。如hover,active,link等属性。如果不想获取这些伪元素的属性值请填写为null。返回值类型和style一样。

一,兼容性解决

 //非行间样式的兼容性解决示例 if(oDiv.currentStyle){      //针对IE      alert(oDiv.currentStyle.width)  }else{      //针对火狐      alert(getComputedStyle(oDiv,null).width)  }  //封装 function getStyle(obj,name){     if(obj.currentStyle){          //针对IE          return obj.currentStyle[name];      }else{          //针对火狐          return getComputedStyle(obj,null)[name]      }  }

0 0
原创粉丝点击