更改按钮颜色 onClick

新手上路,请多包涵

我希望我的 Button 每次点击它时都会改变颜色。但它只会在第一次点击时改变颜色。

我相信问题出在 setColor 函数中。每次我点击 Button 时, count 都会被设置为 1。所以即使我将其设置为 0,它也会在下一次点击时重置为 1。我该如何解决? javascript/html 中是否有可以轻松解决的全局变量?

 <!DOCTYPE html>
<html>
<head>

<script>
function setColor(btn, color){
    var count=1;
    var property = document.getElementById(btn);
    if (count == 0){
        property.style.backgroundColor = "#FFFFFF"
        count=1;
    }
    else{
        property.style.backgroundColor = "#7FFF00"
        count=0;
    }

}
</script>
</head>

<body>

<input type="button" id="button" value = "button" style= "color:white" onclick="setColor('button', '#101010')";/>

</body>
</html>

原文由 user2456977 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.4k
2 个回答

javascript中确实存在全局变量。您可以了解有关 范围 的更多信息,这在这种情况下很有帮助。

您的代码可能如下所示:

 <script>
    var count = 1;
    function setColor(btn, color) {
        var property = document.getElementById(btn);
        if (count == 0) {
            property.style.backgroundColor = "#FFFFFF"
            count = 1;
        }
        else {
            property.style.backgroundColor = "#7FFF00"
            count = 0;
        }
    }
</script>

希望这可以帮助。

原文由 Julien P 发布,翻译遵循 CC BY-SA 3.0 许可协议

1.

 function setColor(e) {
  var target = e.target,
      count = +target.dataset.count;

   target.style.backgroundColor = count === 1 ? "#7FFF00" : '#FFFFFF';
   target.dataset.count = count === 1 ? 0 : 1;
   /*

   () : ? - this is conditional (ternary) operator - equals

   if (count === 1) {
      target.style.backgroundColor = "#7FFF00";
      target.dataset.count = 0;
   } else {
      target.style.backgroundColor = "#FFFFFF";
      target.dataset.count = 1;
   }
   target.dataset - return all "data attributes" for current element,
   in the form of object,
   and you don't need use global variable in order to save the state 0 or 1
  */
}

<input
  type="button"
  id="button"
  value="button"
  style="color:white"
  onclick="setColor(event)";
  data-count="1"
/>

2.

 function setColor(e) {
   var target = e.target,
       status = e.target.classList.contains('active');

   e.target.classList.add(status ? 'inactive' : 'active');
   e.target.classList.remove(status ? 'active' : 'inactive');
}

.active {
  background-color: #7FFF00;
}

.inactive {
  background-color: #FFFFFF;
}

<input
  type="button"
  id="button"
  value="button"
  style="color:white"
  onclick="setColor(event)"
/>

([条件(三元)运算符])

Example-1

Example-2

原文由 Oleksandr T. 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题