在js中正确获取元素的样式值

  在日常的界面制作中,常常需要在js中动态操作元素的样式。一般会使用到obj.style.width之类的获取,但是有时能够获取到样式值,有时不能。在这文章中,主要解释一下这种现象出现的原因和解决方法。

样式种类

css的样式主要分为三种:

  • 内联样式: 也称为行内样式,直接写在DOM元素的style属性内;
  • 内嵌样式:写在HTML的</style><style>中的样式
  • 外部样式:由link标签引入的css文件中的样式

以上样式的优先级:内联>内嵌>外部

首先,来测试一下这三种样式使用obj.style.width格式的样式值获取情况:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<head>
<meta charset="UTF-8">
<title>get style</title>
<style>
<!-- 嵌入样式 -->
.box {
height: 200px;
}
</style>
<!-- 引入外部样式 -->
<link rel="stylesheet" href="./index.css">
</head>
<body>
<!-- 行内样式 -->
<div class="box" style="width: 100px;"></div>
</body>

1
2
// index.css
.box { background-color: orange; }
1
2
3
4
5
//JavaScript
var box = document.getElementsByClassName('box')[0];
console.log(box.style.width);
console.log(box.style.height);
console.log(box.style.backgroundColor);

得到的测试结果为:

1
2
3
'100px'
''
''

由以上的结果我们可以得出一个结论:
style只能获取行内样式的值,无法获取嵌入式样式和外部样式的值

那么我们怎样才能获取到内嵌样式和外部样式呢?

解决方法

在IE浏览器使用obj.currentStyle.width格式,在FF或Chrome浏览器使用document.defaultView.getComputedStyle(obj,false).width格式

1
2
3
4
5
6
7
8
9
10
11
12
// currentStyle: IE下获取元素样式的值
if ( box.currentStyle ) {
console.log( 'this is IE.' );
console.log( box.currentStyle.width );
console.log( box.currentStyle.height );
console.log( box.currentStyle.backgroundColor );
} else {
// chorme and firefox
console.log( document.defaultView.getComputedStyle(box, false).width );
console.log( document.defaultView.getComputedStyle(box, fasle).height );
console.log( document.defaultView.getComputedStyle(box, false).backgroundColor );
}

PS:“DOM2级样式”增强了document.defaultView,提供了getComputedStyle()方法。这个方法接受两个参数:要取得计算样式的元素和一个伪元素字符串(例如“:after”)。如果不需要伪元素信息,第二个参数可以是null。getComputerStyle()方法返回一个CSSStyleDeclaration对象,其中包含当前元素的所有计算的样式。

其语法为:document.defaultView.getComputedStyle('元素', '伪类')

综上,我们可以写一个获取元素样式值的方法:
(实际上,使用defaultView基本上是没有必要的,getComputedStyle本身就存在window对象之中)

1
2
3
4
5
6
7
8
9
10
11
12
13
function getStyle(obj,attr,value){
if(!value){
if(obj.currentStyle){ //IE浏览器下
return obj.currentStyle(attr);
}
else{
return obj.getComputedStyle(attr,false); //ff,safari,opera,chrome浏览器下
}
}
else{
obj.style[attr]=value; //修改样式,style属性能写能读
}
}