How do you create a toggle button?

后端 未结 15 2933
名媛妹妹
名媛妹妹 2020-11-27 11:46

I want to create a toggle button in html using css. I want it so that when you click on it , it stays pushed in and than when you click it on it again it pops out.

15条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 12:17

    Here is one of the example/variant (more detail described) of ToggleButton using jQuery with implementation.

    1st we will create container for our ToggleButton using classic HTML and

    
       
      
    
    

    Next we will define function for toggling our button. Our button actually is the usual which we will be styling to represent value toggling.

    function toggleButton(button) {
    
    var _for = button.getAttribute('for'); // defining for which element this label is (suppose element is a checkbox (bec. we are making ToggleButton ;) )
    var _toggleID = 'input#'+_for; // composing selector ID string to select our toggle element (checkbox)
    var _toggle = $( _toggleID ); // selecting checkbox to work on
    var isChecked = !_toggle.is(':checked'); // defining the state with negation bec. change value event will have place later, so we negating current state to retrieve inverse (next).
    
    if (isChecked)
        $(button).addClass('SelectedButtonClass'); // if it is checked -> adding nice class to our button (

    Function is implemented in a reusable way. You can use it for more than one, two or even three ToggleButtons you've created.

    ... and finally ... to make it work as expected, we should bind toggle function to an event ("change" event) of our improvised button (it will be click event bec. we are not altering the checkbox directly, so no change event can be fired for ).

    $(document).ready(function(){
    
        $("#some_feature_label").click(function () {
            toggleButton(this); // call function with transmitting instance of a clicked label and let the script decide what was toggled and what to do with it
        });
    
        $("#some_other_feature_label").click(function () {
            toggleButton(this); // doing the same for any other feature we want to represent in a way of ToggleButton
        });
    
    });
    

    With CSS we can define backgorund-image or some border to represent the change in value whilst will do the job for us in altering the value of a checkbox ;).

    Hope this helps someone.

提交回复
热议问题