currentStyle、getComputedStyle

时间:2023-03-09 01:48:58
currentStyle、getComputedStyle

element.offsetWidth:

返回元素的宽度,包括边框和内边距。

element.offsetHeight:

返回元素的高度,包括边框和内边距。

currentStyle:

获取计算后的样式,也叫当前样式、最终样式。优点:可以获取元素的最终样式,包括浏览器的默认值,而不像style只能获取行间样式,所以更常用到。注意:不能获取复合样式如background属性值,只能获取单一样式如background-color等。currentStyle 在ie、opera上是可行的,无法适用于所有浏览器的。

getComputedStyle(
obj , false ):

是支持 w3c (FF12、chrome
14、safari):
在FF新版本中只需要第一个参数,即操作对象,第二个参数写“false”也是大家通用的写法,目的是为了兼容老版本的火狐浏览器。

所以可以这样来写兼容:

 var obj= document.getElmentById("id");
var getStyle = function (obj,attr) {
if(obj.currentStyle){
//
return parseInt(obj.currentStyle[attr]);
}else{
return parseInt(getComputedStyle(obj,false)[attr]);
}
}