首页 > 解决方案 > 我有一个按钮,我需要在第一次单击时打开颜色并在第二次单击时更改回原始颜色

问题描述

我可以在第一次单击时使按钮更改颜色,但在第二次单击时不能。不知道如何执行。控制台日志按预期设置为 true。

        var clicked = true,

            button = document.getElementById("buttonProps");

        button.addEventListener("click", function () {

            if (clicked) {
                this.style.backgroundColor = "skyblue";
            } else {

                this.style.backgroundColor = "lightgray";
            }

        });
        console.log(clicked)

标签: javascriptif-statementdom-events

解决方案


您需要切换单击的变量

var clicked = true

button = document.getElementById("buttonProps");

button.addEventListener("click", function() {

  if (clicked) {
    this.style.backgroundColor = "skyblue";
  } else {
    this.style.backgroundColor = "lightgray";
  }
  clicked = !clicked

});
console.log(clicked)

推荐阅读