更改按钮颜色onClick

时间:2014-11-14 19:26:47

标签: javascript html button onclick global

我希望每次点击它时我的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>

4 个答案:

答案 0 :(得分:10)

javascript中确实存在全局变量。您可以了解有关scopes的更多信息,这些信息对您有所帮助。

您的代码可能如下所示:

<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 :(得分:6)

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

([conditional (ternary) operator])

Example-1

Example-2

答案 2 :(得分:0)

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

}

答案 3 :(得分:0)

使用jquery,尝试一下。 如果您的按钮ID是说id = clickme

$(“ clickme”)。on('çlick',function(){

$(this).css('background-color','grey'); .......