jquery change button color onclick

后端 未结 5 520
自闭症患者
自闭症患者 2021-02-04 11:04

I have multiple buttons that I use when people answer a question. How would I get the buttons to change colors when a person clicks on the button? I do not know jquery, I have b

5条回答
  •  面向向阳花
    2021-02-04 11:10

    I would just create a separate CSS class:

    .ButtonClicked {
        background-color:red;
    }
    

    And then add the class on click:

    $('#ButtonId').on('click',function(){
        !$(this).hasClass('ButtonClicked') ? addClass('ButtonClicked') : '';
    });
    

    This should do what you're looking for, showing by this jsFiddle. If you're curious about the logic with the ? and such, its called ternary (or conditional) operators, and its just a concise way to do the simple if logic to check if the class has already been added.

    You can also create the ability to have an "on/off" switch feel by toggling the class:

    $('#ButtonId').on('click',function(){
        $(this).toggleClass('ButtonClicked');
    });
    

    Shown by this jsFiddle. Just food for thought.

提交回复
热议问题