有如下代码:


1 2 3

​div {​​​​​​​​width​​​​: ​​​​200px​​​​;​​​​}​




1 2 3

​<​​​​div​​​​id="aa" style="height: 100px;">​​​​​​​​xxxx​​​​</​​​​div​​​​>​




1 2 3 4 5 6 7 8 9

​var​​​​div = document.getElementById(​​​​"aa"​​​​);​​​​var​​​​h = div.style.height;​​​​var​​​​w = div.style.width;​​​​console.log(h); ​​​​//100px​​​​console.log(w); ​​​​//这个结果为空​



因为这种方法只能获取dom元素的行内样式,当这个div的宽度是在css中设置的,用这种方法得到的就是空值。

有两种方法可以解决这个问题。

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



1 2 3 4 5

​var​​​​div = document.getElementById(​​​​"aa"​​​​);​​​​var​​​​w = getComputedStyle(div,​​​​false​​​​)[​​​​"width"​​​​]​​​​console.log(w); ​​​​//200px​


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


2.nodeObj.currentStyle['attr'];

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

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


1 2 3 4 5

​var​​​​div = document.getElementById(​​​​"aa"​​​​);​​​​var​​​​w = div.currentStyle[​​​​"width"​​​​];​​​​console.log(w); ​​​​//200px​


这个方法在谷歌浏览器报错,但是在ie浏览器可以打印出结果;


综上所述,我们可以写一个方法来获取非行间样式:


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

​var​​​​div = document.getElementById(​​​​"aa"​​​​);​​​​var​​​​w = getAttr(div, ​​​​"width"​​​​);​​​​console.log(w);​​​​function​​​​getAttr(obj, attr) {​​​​​​​​var​​​​style;​​​​​​​​if​​​​(window.getComputedStyle) {​​​​​​​​style = getComputedStyle(obj, ​​​​false​​​​)[attr]; ​​​​//主流浏览器​​​​​​​​} ​​​​else​​​​{​​​​​​​​style = obj.currentStyle[attr]; ​​​​//兼容IE​​​​​​​​}​​​​​​​​return​​​​style;​​​​}​