javascript中获取非行间样式的方法

我们都知道一般在javascript中获取样式一般用的是nodeObj.style.attr这个属性的,但是这个属性只能获取行间样式非行间样式比如写在样式表中的样式那么用nodeObj.style.attr获取就是一个空字符。

今天我们来介绍下要获取节点计算后的样式就是不一定写在行间样式的方法。

1:window.getComputedStyle(obj,false)['attr']方法

这是BOM(浏览器window对象)提供的方法 ,所以可以直接写成getComputedStyle(nodeObj,false),省略前面的window对象,该方法有两个参数,第一个是要获取样式的节点对象;第二个可以写成任何的字符一般写成false或者null,这里最好是用false因为用null IE9+会有问题;后面直接跟要获取的样式(写在方括号中)即可。这个方法的返回值为一个对象,为计算后的样式的属性值对的集合。比如要获取某个div宽度。那么可以直接写成 var style=getComputedStyle(div,false)['width']; alert(style);

但是IE8 以下是不支持window.getComputedStyle(obj,false)['attr']方法

2:nodeObj.currentStyle['attr'];

node.currentStyle,该属性返回的也是是一个对象,也是计算后的样式的属性值对的集合。比如要获取某个div宽度。那么可以直接写成 

var style=div.currentStyle['width']; alert(style);

3:为了兼容性我们可以将其封装为一个函数,提供一个统一的获取计算后的样式方法如下:

html:

<body>

<div style="width:500px"></div>

</body>

css:

  <style type="text/css"> 

     body,*{margin: 0;padding: 0;}

     div{width: 300px;height: 300px;background: blue;border: 10px  solid #000;}

     </style>

js:

<script type="text/javascript">

window.οnlοad=function(){

      var div=document.getElementsByTagName("div")[0];

      var style=getAttr(div,'width')

      alert(style);   

}

//我们把它们封装为一个函数,注意了在全局下定义的函数的都会默认设置为window对象的方法,所以以后我们调用方法的时候就可以直接用然后省略前面的对象,当然了你这样var style=window.getAttr(div,'width');调用也是木有问题的。

function getAttr(obj,attr){  

  var style;

     if(obj.currentStyle){   //当有这个属性的时候currentStyle

style=obj.currentStyle[attr]; //兼容IE 我测试的是ie5+

     }

     else{

style=getComputedStyle(obj,false)[attr]; //主流浏览器

     }

     return style;

}

</script>

发布了24 篇原创文章 · 获赞 8 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43869192/article/details/96108186