通过javascript获取给定div继承的css值

时间:2011-03-07 20:40:23

标签: javascript css

鉴于页面的DIV,我想通过Javascript获得A元素继承的样式表。

所以,例如

<html>
<head>
BODY { font-size:18px; }
A { color: red; }
#layer A { color: green; }
</head>

<div id="layer">
<a href="xxx">yyy</a>
</div>

</body>
</html>

我想要一个JS函数,比如getStyle(“layer”,“a”),它会返回“font-size:18px; color:green;” ,这是应用于该div元素的所有样式,从所有样式表继承。

谢谢!

1 个答案:

答案 0 :(得分:0)

getComputedStyle正是您要找的。

我在JSFiddle上做了这个:http://jsfiddle.net/6MmAf/1/

<div id="layer">
<a href="xxx" id="thelink">yyy</a>
</div>

BODY { font-size:18px; }
A { color: red; }
#layer A { color: green; }

window.alert(
    getComputedStyle(
        document.getElementById('thelink')
    ).fontSize
);
// it alerts 18px, which is inherited from BODY in css