getComputedStyle function

[b]Getting an element's style[/b]
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 <p> elements, but then one of the <p>
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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值