Switch color of button on click (and revert color

2019-07-21 09:12发布

I have three buttons, and want to change the color of the button on being selected. As you will see, I am able to change the color on selection, but I need buttonA to return to its original color when buttonB is selected (at which point buttonB should take on the selected color) and so on. Currently each button selected takes on the selected color, but buttons do not return to their original color.

Please see this fiddle: http://jsfiddle.net/Fwqv8/

This is the script:

jQuery(document).ready(function(){
   jQuery('button.account').click(function() {
      jQuery(this).removeClass("account");
      jQuery(this).addClass("btn-success");
   });
});

Ideally there will be a default button (buttonA) which has the selected color when the page loads initially.

Help would be greatly appreciated. Thank you.

5条回答
对你真心纯属浪费
2楼-- · 2019-07-21 09:46
jQuery(function(){
    var $acctButtons = jQuery(".account");
    jQuery('button.account').click(function() {
        $acctButtons.removeClass("btn-success");
        jQuery(this).addClass("btn-success");
    });
});
查看更多
▲ chillily
3楼-- · 2019-07-21 09:52

YOU CAN USE TOGGLECLASS FOR SINGLE BUTTON

LIVE DEMO

查看更多
时光不老,我们不散
4楼-- · 2019-07-21 09:53

JS

jQuery(document).ready(function() {

    $('.btn').click(function() {
        $('.btn').removeClass("btnSelected");
        $(this).addClass("btnSelected");
    })

});

CSS

.btn{
  width:100px;
  height:20px;
  display:inline-block;
  background-color:red;
}
.btnSelected{
  background-color:green;
}

HTML

<div id="btn1" class="btn">Button 1</div>
<div id="btn2" class="btn">Button 2</div>
<div id="btn3" class="btn">Button 3</div>

Try @ codebins

查看更多
家丑人穷心不美
5楼-- · 2019-07-21 10:02

You can use:

jQuery(document).ready(function(){
        jQuery('button.account').click(function(){
            var that = this;
            jQuery('button.account').each(function(i, btn){
                jQuery(this).addClass("btn-danger");
                jQuery(this).removeClass("btn-success");
            });
            jQuery(that).addClass("btn-success");
        });
     });

This code does all your buttons switch back to their default state on click. Only the clicked button will stay (in your case) "green".

An default button can easily been done by setting the default class in your markup.

查看更多
The star\"
6楼-- · 2019-07-21 10:08

You could remove the btn-success class on all buttons in the onclick function, then add the class only to the newly selected

jQuery(document).ready(function(){
   jQuery('button.account').click(function() {
      jQuery('button.btn-success').removeClass('btn-success');
      jQuery(this).removeClass("account");
      jQuery(this).addClass("btn-success");
   });
});

Or you could have an array with the currently selected buttons, and removing the btn-success class on a newly clicked button

http://jsfiddle.net/Fwqv8/3/

查看更多
登录 后发表回答