JavaScript通过单击设置新的背景颜色

时间:2014-04-07 09:48:20

标签: javascript css html5

无法更改下面部分的背景颜色onclick,试图弄清楚什么是不正确的。

<!DOCTYPE html>
<html>
    <head>
        <script>
            window.onload=function(){
                document.getElementById("top_bar").getPropertyValue("background-color").onclick=function(){
                    this="green";    
                }
            }
        </script>
    </head>
    <body>
        <section id="top_bar"></section>
    </body>
</html>

2 个答案:

答案 0 :(得分:2)

document.getElementById("top_bar").addEventListener('click', function() {
    this.style.backgroundColor = "green";
}
// I like the above code better, because you don't see the `onclick` in the DOM, but this would be more like your approach:
document.getElementById("top_bar").onclick = function() {
    this.style.backgroundColor = "green";
}

详细了解getPropertyValue函数here

答案 1 :(得分:1)

background-color属性上没有onclick属性 您必须参考按钮的onclick事件,然后在按钮上设置background-color属性。 在这里你可以看到:

替换它:

 window.onload=function(){
            document.getElementById("top_bar").getPropertyValue("background-color").onclick=function(){
                this="green";    
            }
        }

用这个:

 window.onload=function(){
            document.getElementById("top_bar").onclick=function(){
                this.style.setProperty ("background-color", "green", null);
            }
        }