开发者

Cannot retrieve style using js

<html>
<head>
<style>
#menu{
color :red;
}
</style>
</head>
<body>
<div id="menu">
ABCXTZ
</div>
</body>
<script>
a = document.getElementById('menu');
alert(a.style.color);
</script>
</html

What I retrieve 开发者_JAVA技巧is just an empty box.


To get the computed style you have to go a bit of a different route, like this:

var a = document.getElementById('menu');
if(document.defaultView && document.defaultView.getComputedStyle) {
    alert(document.defaultView.getComputedStyle(a, null).getPropertyValue("color"));
} else if(a.currentStyle) {
    alert(a.currentStyle.color);
}

You can give it a try here, getting .style gets the properties defined on the element itself, not those inherited from the rules it matches. The above uses the getComputedStyle() if available and in the case of IE, falls back to .currentStyle.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜