Toggle Twitter Bootstrap button class when active

前端 未结 3 687
野性不改
野性不改 2020-12-31 05:13

In twitter bootstrap, I was looking for a way to allow a button to be the default color when not active. Once a button is active, I wanted to change the color of it. I loo

3条回答
  •  情书的邮戳
    2020-12-31 06:14

    By adding class-toggle as an attribute to the button equaling what you would like to go to once the button is pressed and adding the following jQuery, you will get the result described above.

    $('.btn-group > .btn, .btn[data-toggle="button"]').click(function() {
    
            if($(this).attr('class-toggle') != undefined && !$(this).hasClass('disabled')){
                var btnGroup = $(this).parent('.btn-group');
    
                if(btnGroup.attr('data-toggle') == 'buttons-radio') {
                    btnGroup.find('.btn').each(function() {
                        $(this).removeClass($(this).attr('class-toggle'));
                    });
                    $(this).addClass($(this).attr('class-toggle'));
                }
    
                if(btnGroup.attr('data-toggle') == 'buttons-checkbox' || $(this).attr('data-toggle') == 'button') {
                    if($(this).hasClass('active')) {
                        $(this).removeClass($(this).attr('class-toggle'));
                    } else {
                        $(this).addClass($(this).attr('class-toggle'));
                    }
                 }
    
              }
    
    
          });
    

    Then the button would look like

    
    

    If you want to do it with a button group as well it works the same way. Just add the class-toggle to each button in the group.

    The jsfiddle

    UPDATE

    I have modified and created a gist to have a better response when starting you button with a class. Toggle Twitter Bootstrap Classes

    UPDATE

    I have made a change to fix the bug that appears when you click on an active radio button

    Find it here

提交回复
热议问题