取非行间样式

IE获取非行间样式:currentStyle

chrome、FireFox获取非行间样式:getComputedStyle  getComputedStyle带两个参数,第一个是对象名,第二个随便填都行,一般写false。getComputedStyle(oDiv,false)

获取非行间样式代码:

 1 if(oDiv.currentStyle){
 2 
 3   alert(oDiv.currentStyle.width);  //IE
 4 
 5 }
 6 
 7 else{
 8 
 9   alert(getComputdeStyle(oDiv,false).width);  //FF
10 
11 }

取样式在项目中会经常用到,如果每次都要用if else来写会很麻烦,所以可以把取样式的代码封装起来,要用的时候只要调用就可以。

 1 fuction getStyle(obj,name){
 2 
 3   if(obj.currentStyle){
 4 
 5     return obj.currentStyle[name];
 6   }
 7 
 8   else{
 9 
10     return getComputedStyle(obj,false)[name];
11   }

调用 getStyle(oDiv,width)

复合样式:指本身由很多项组成的,如background 有background-image background-color。

currentStyle和getComputedStyle获取非行间样式只能获取单一样式不能获取复合样式。所以要获取背景颜色就要用background-color。

原文地址:https://www.cnblogs.com/52css/p/2937071.html