在网页中设置某元素的样式,可以有以下几种方式:
| 通过外部的 CSS 样式表 |
<!-- some.html --> <link rel="stylesheet" type="text/css" href="some.css"> /* some.css */
#someid {background-color: blue;}
|
| 通过内嵌的 CSS 样式表 |
<!-- some.html -->
<style> #someid {background-color: blue;} </style>
|
| 通过元素的 style 属性 |
<!-- some.html --> <div id="someid" style="background-color: blue;"></div> |
| 通过 DOM2 提供的 API |
/* some.js */
var elem = document.getElementById("someid");
elem.style.backgroundColor = "blue";
|
其中前面三种是在网页文件中静态地设置元素样式,而最后一种方式是通过 JavaScript 动态地改变元素的样式。
在 JavaScript 中,元素的 style 属性只保存前面后两种方式设置的样式。因此,如果我们需要读取该元素的实际样式,不能用这个属性。这时需要使用 getComputedStyle 函数。例子如下:
var elem = document.getElementById("someid");
alert(window.getComputedStyle(elem, null).backgroundColor);
其中在 getComputedStyle 函数的第二个参数可以指明元素的伪类。这个参数在旧版本 Firefox 中不可省略。
这个 getComputedStyle 函数在 IE6 - IE8 中没有,此时我们可以改用 IE 提供的 currentStyle 属性。例如:
var elem = document.getElementById("someid");
alert(elem.currentStyle.backgroundColor);
注意 getComputedStyle 得到的样式和 currentStyle 一样都是只读的。
为了方便使用,我们可以模拟 jQuery 写一个 css() 函数。如下:
$.fn.css = function(property, value) {
if (arguments.length >= 2) {
this.each(function() {
this.style[property] = value;
});
return this;
} else {
var style = window.getComputedStyle ? window.getComputedStyle(this[0], null) : this[0].currentStyle;
return style[property];
}
}
参考资料:
[1] window.getComputedStyle - Document Object Model (DOM) | MDN
[2] Can I use getComputedStyle
[3] JavaScript - Get Styles - quirksmode
[4] getComputedStyle - ie test drive
[5] currentStyle object (Internet Explorer)
[6] 获取元素CSS值之getComputedStyle方法熟悉
[7] $.fn.css() | jQuery API Documentation