Change button background color on toggle

无人久伴 提交于 2019-12-20 07:33:15

问题


I have a button and i want to change its background color to white on click, and then when i click another time it return back to its original background color, how can i do that? here is my code:

 $(document).ready(function () {
            $("button").click(function () {
    $(this).css("background-color", "#FFF");
                    });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Hello</button>

回答1:


All you need to do is add some sort of toggle boolean, in this example it's the var named 'white'.

var white = false
var bgcolor;
$(document).ready(function () {
    $("button").click(function () {
        if (white = !white) {
            bgcolor = $(this).css('backgroundColor');
            $(this).css("background-color", "#FFF");
        } else {
            $(this).css("background-color", bgcolor);
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Hello</button>



回答2:


The easiest way to do this would be to set the background-color using a CSS class, then call toggleClass() in the click event handler, something like this:

$("button").click(function() {
  $(this).toggleClass('foo');
});
button { 
  background-color: #000; 
  color: #FFF;
}
button.foo { 
  background-color: #FFF; 
  color: #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Hello</button>



回答3:


Try this, simple JS solution;

$(document).ready(function () {

   var i=0;
   $("button").click(function () {

      if(i==0){
          $(this).css("background-color", "#FFF");
          i=1;
      }
      else{
          $(this).css("background-color", "#000"); 
          i=0; 
      }
   });
});



回答4:


Record the initial button color, then set/reset based upon state flag

$(function(){
  var buttoncolor = $('button').css('background-color');
  var state=true;
  $('button').click(function(){
     if (state )
     {
        $('button').css('background-color','white');
     }
     else
     {
        $('button').css('background-color', buttoncolor );
     }
     state=!state;
  })
});



回答5:


$(document).ready(function() {
  $("button").click(function() {
    $(this).toggleClass("new");
  });
});
.new {
  background-color: red
}

button {
  background-color: white
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Hello</button>
  1. Use a class with css
  2. Use .toggleClass() to switch the class every click

    Description: Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the state argument.



来源:https://stackoverflow.com/questions/43041344/change-button-background-color-on-toggle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!