无法使用js检索样式

时间:2010-08-14 10:18:53

标签: javascript css dhtml

<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

我检索的只是一个空盒子。

1 个答案:

答案 0 :(得分:4)

要获得计算样式,您必须采用不同的路径,例如:

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,获取.style获取在元素本身上定义的属性,而不是从它匹配的规则继承的属性。以上使用getComputedStyle()(如果可用),如果是IE,则回退到.currentStyle