首页 | 最近更改 | 编辑本页 | 较早版本

可打印版 | 免责声明

Not logged in
登录 | 帮助
 

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>

Image:permalink.gif 例子:获取由元素的 style 属性定义的样式

var p1elem, p2elem;
p1elem = document.getElementById('p1');
p2elem = document.getElementById('p2');
alert(p1elem.style.color); // 将显示一个空串
alert(p2elem.style.color); // 将显示"blue"

用这种方法获得的信息并不是很有用,所以您不应该再用 element.style 来得到元素的样式。 (您可以用它来设置元素的样式,详见设置元素样式。)

那么您该用什么方法来替代呢? getComputedStyle() 函数。

Image:Permalink.gif 例子:获取元素的实际样式

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

实例


← 添加 CSS 样式
设置元素样式 →

取自"http://wiki.mozcn.org/index.php/Firefox:Dive_Into_Greasemonkey/4.14._Getting_an_element%27s_style"

本页面已经被浏览2352次。 最后更改02:38 2005年11月20日. 本站内容在创作共用署名-非商业用途-保持一致条款下发布。


[首页]
首页
最近更改
随机页面
新闻动态

编辑本页
讨论本页
较早版本
链入页面
链出更改

特殊页面
错误报告