简体   繁体   English

无法使用javascript获取html元素的颜色

[英]Cannot get color of html element using javascript

I cannot get the colour of an html element using javascript until after it has been set in the script. 在脚本中设置html元素之前,无法获得html元素的颜色。 For example: 例如:

<html>
<head>
    <style media="screen" type="text/css">
        h1 {
            color: purple;
        }
    </style>
    <script type="text/javascript">
        function test() {
            var header = document.getElementsByTagName("h1")[0];
            alert("Colour: " + header.style.color); // Does not get the correct colour
            header.style.color = "yellow";
            alert("Colour: " + header.style.color); // Gets the correct colour
        }
    </script>
</head>
<body onload="test();">
    <h1>Header</h1>
</body>
</html>

I would expect the first alert to show "Colour: purple" as set in the css and the second to show "Colour: yellow" from the function itself. 我希望第一个警报显示css中设置的“颜色:紫色”,第二个警报从功能本身显示“颜色:黄色”。 However, the first alert simply shows "Colour: ". 但是,第一个警报仅显示“ Colour:”。 In both cases, the colour of the element is correct and verified using firebug. 在这两种情况下,元素的颜色都是正确的,并使用萤火虫进行了验证。

对于通过CSS设置样式的元素,要获取其呈现的样式,您需要使用getComputedStyle

alert(getComputedStyle(header).color) // the color you want

element.style.property gets only CSS properties assigned directly on the element. element.style.property仅获取直接在元素上分配的CSS属性。 To get the actual property value no matter where it was assigned (external stylesheet or inline) use window.getComputedStyle(element).property , where element is a reference to your element. 要获得实际的属性值,无论将其分配到何处(外部样式表或内联),请使用window.getComputedStyle(element).property ,其中element是对元素的引用。

So in your example it would be: 因此,在您的示例中它将是:

alert("Colour: " + getComputedStyle(header).color);

See definition: https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle 查看定义: https : //developer.mozilla.org/zh-CN/docs/Web/API/Window/getComputedStyle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM