单击时更改按钮颜色

Change Button color onClick

本文关键字:按钮 颜色 单击      更新时间:2023-09-26

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

我认为问题出在setColor功能上。每次我点击Buttoncount都设置为 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>

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>

希望这有帮助。

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" 
/>

阿拉伯数字。

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

每次setColor被击中时,您都会设置 count = 1。您需要在函数范围之外定义count。例:

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

使用 jquery,试试这个。如果您的按钮 ID 是 ID = 点击我

$("clickme").on('çlick', function(){
  **$(this).css('background-color', 'grey');
.......