无法使用DOM获取背景颜色

Dor*_*hen 3 html javascript css dom

我正在尝试获取已编写在不同CSS文件中的元素背景样式.问题是我无法获得CSS文件中编写的样式.

另一方面,可以获得已经写在HTML文档上的样式.

CSS代码

#try2
{ 
    background-color:yellow;
}
body
{
    background-color:gray;
}
td, th{
    border: 1px solid black;
}
Run Code Online (Sandbox Code Playgroud)

HTML代码

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=windows-1255" />
        <link rel="stylesheet" type="text/css" href="html.css">
        <script type="text/javascript" src="external.js"></script>
    </head>
    <body>
        <table>
            <tr>
                <td id = "try1" style="background-color:green;"><p id="ChosenColor3"> htmlfile</p></td>
            </tr>
            <tr>
                <td id = "try2"><p id="ChosenColor4"> css file</p></td>
                <td><button id="bestRated3" onclick = arrayTest()> ?.? </button></td>
                <td><button id="submitForm" onclick = submit()> end</button></td>
            </tr>
            <tr>
                <td><h1 id="ChosenColor5"> text </h1></td>  
            </tr>
        </table>
    </body>
    <script>
        window.onload=aaa();
        function aaa()
        {
            var x = document.getElementById("try2");
            alert(x.style.background);
        }
    </script>     
</html>
Run Code Online (Sandbox Code Playgroud)

如您所见,我得到的消息是空的.如果我将ID更改为" try1",它将显示.

Jon*_*Jon 7

style属性允许您读取和写入每个元素的styleHTML属性的值(所谓的内联样式) - 它不考虑样式表.

要发现您必须使用的CSS属性的真正价值window.getComputedStyle,例如:

alert(getComputedStyle(x, null).getPropertyValue("background-color"));
Run Code Online (Sandbox Code Playgroud)

看到它在行动.

请注意,getComputedStyleIE 8或更早版本不支持.