Firefox:Dive Into Greasemonkey/4.14. Getting an element's style
Mozilla中文Wiki
您的位置:Dive Into Greasemonkey → 公用模式 → 取得元素样式
[编辑]
4.14. 取得元素样式
当多个CSS规则同时应用到某个元素上时,获取这个元素的实际样式有时候是有帮助的。您可能会简单的认为,通过元素的 style 属性就可以得到,这样的话您就错了。它只会返回 style 属性的内容。要获得元素的最终样式(包括在外部定义的样式),您需要使用 getComputedStyle 函数。
为了说明这点,我们建立一个测试页面。它首先对页面中所有的<p>元素定义了一个样式,但随后其中的一个<p>元素用它的 style 属性又重新定义了它的样式。
<html>
<head>
<title>Style test page</title>
<style type="text/css">
p { background-color: white; color: red; }
</style>
</head>
<body>
<p id="p1">This line is red.</p>
<p id="p2" style="color: blue">This line is blue.</p>
</body>
</html>
var p1elem, p2elem;
p1elem = document.getElementById('p1');
p2elem = document.getElementById('p2');
alert(p1elem.style.color); // 将显示一个空串
alert(p2elem.style.color); // 将显示"blue"
用这种方法获得的信息并不是很有用,所以您不应该再用 element.style 来得到元素的样式。 (您可以用它来设置元素的样式,详见设置元素样式。)
那么您该用什么方法来替代呢? getComputedStyle() 函数。
var p1elem, p2elem, p1style, p2style;
p1elem = document.getElementById('p1');
p2elem = document.getElementById('p2');
p1style = getComputedStyle(p1elem, '');
p2style = getComputedStyle(p2elem, '');
alert(p1style.color); // will display "rgb(255, 0, 0)"
alert(p2style.color); // will display "rgb(0, 0, 255)"
[编辑]
实例
- Butler (http://diveintomark.org/projects/butler/butler.user.js)
- Zoom textarea (http://diveintogreasemonkey.org/download/zoomtextarea.user.js)
设置元素样式 →

![[首页]](/stylesheets/images/wiki.png)