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

JavaScript setting new background-color by click

本文关键字:背景 颜色 设置 单击 JavaScript      更新时间:2023-09-26

无法在点击时更改下面部分的背景颜色,试图找出不正确的地方。

<!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>
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功能的更多信息

背景颜色属性上没有 onclick 属性必须引用按钮的 onclick 事件,然后在按钮上设置背景色属性。在这里,您可以看到如何:

替换此内容:

 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);
            }
        }