2010-08-14 27 views
1
<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 

我检索的只是一个空框。使用js无法检索样式

回答

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