jQuery onclick toggle class name

前端 未结 2 1978
盖世英雄少女心
盖世英雄少女心 2020-11-27 17:52

Using jQuery, how do I toggle classA to classB on click going from:

Switch
相关标签:
2条回答
  • 2020-11-27 18:24

    you can use toggleClass() to toggle class it is really handy.

    case:1

    <div id='mydiv' class="class1"></div>
    
    $('#mydiv').toggleClass('class1 class2');
    
    output: <div id='mydiv' class="class2"></div>
    

    case:2

    <div id='mydiv' class="class2"></div>
    
    $('#mydiv').toggleClass('class1 class2');
    
    output: <div id='mydiv' class="class1"></div>
    

    case:3

    <div id='mydiv' class="class1 class2 class3"></div>
    
    $('#mydiv').toggleClass('class1 class2');
    
    output: <div id='mydiv' class="class3"></div>
    
    0 讨论(0)
  • 2020-11-27 18:31

    jQuery has a toggleClass function:

    <button class="switch">Click me</button>
    
    <div class="text-block collapsed pressed">some text</div>
    
    <script>    
        $('.switch').on('click', function(e) {
          $('.text-block').toggleClass("collapsed pressed"); //you can list several class names 
          e.preventDefault();
        });
    </script>
    
    0 讨论(0)
提交回复
热议问题