为了演示,我们创建一个简单的测试页面。它首先对页面中所有的 <p> 元素定义了同一个样式,但随后对其中的一个 <p> 元素用它的 style 属性重新定义了样式。
<html>
<head>
<title>样式测试页</title>
<style type="text/css">
p { background-color: white; color: red; }
</style>
</head>
<body>
<p id="p1">这行是红色的。</p>
<p id="p2" style="color: blue">这行是蓝色的。</p>
</body>
</html>例 4.17. 获取由元素的 style 属性定义的样式
var p1elem, p2elem;
p1elem = document.getElementById('p1');
p2elem = document.getElementById('p2');
alert(p1elem.style.color); // 提示为空字符串
alert(p2elem.style.color); // 提示 "blue"用这种方法获得的信息并不是很有用,所以您不应该再用 element.style 来获取单独的样式。 (您可以用它来设置元素的样式,详见设置元素样式。)
那么您该用什么方法来取代它呢?getComputedStyle()。
例 4.18. 获取元素的真实样式
var p1elem, p2elem, p1style, p2style;
p1elem = document.getElementById('p1');
p2elem = document.getElementById('p2');
p1style = getComputedStyle(p1elem, '');
p2style = getComputedStyle(p2elem, '');
alert(p1style.color); // 提示 "rgb(255, 0, 0)"
alert(p2style.color); // 提示 "rgb(0, 0, 255)"设置元素样式 →