ITeye博客

getComputedStyle function

tory320 · 2009-02-20 16:42 · javascript · Markdown

Getting an element's style It is occasionally useful to get a specific element's actual style, after all CSS rules have been applied. You might naively assume that an element's style property will give you this, but you would be mistaken. That only returns the contents of the element's style attribute. To get the final style (including any styles defined in external stylesheets), you need to use the getComputedStyle function. To illustrate this, let's create a simple test page. It defines a style for all elements, but then one of the elements overrides that with its style attribute.

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

Example: Get the styles defined by an element's style attribute

var p1elem, p2elem;
p1elem = document.getElementById('p1');
p2elem = document.getElementById('p2');
alert(p1elem.style.color); // will display an empty string
alert(p2elem.style.color); // will display "blue"

That wasn't terribly helpful, and you should never use element.style to get individual styles. (You can use it to set individual styles; see Setting an element's style.) So what should you use instead? getComputedStyle(). Example: Get the actual style of an element 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)"

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。