How to toggle classes on click?

2019-03-06 23:55发布

问题:

I know this is a simple question but I have been playing around with no success. I have the following code

<a id="mute"><i class="icon-volume"></i></a>

I want to be able to toggle the class .icon-volume to .icon-volume-off when clicking.

After anyone who can help! Thanks

回答1:

You could use jQuery

$('#mute').on('click', function () {
    var el = $(this).find('i');
    if (el.hasClass('icon-volume')) {
         el.removeClass('icon-volume');
         el.addClass('icon-volume-off');
    } else {
        el.removeClass('icon-volume-off');
        el.addClass('icon-volume');
    }
});

Or you could just add the icon-volume-off class and make sure its css takes precedence over the icon-volume class

$('#mute').on('click', function () {
    var el = $(this).find('i');
    if (el.hasClass('icon-volume-off')) {
         el.removeClass('icon-volume-off');
    } else {
        el.addClass('icon-volume-off');
    }
});


回答2:

Try

    var a = document.getElementById("mute");
    a.onclick = function(e){
     var cl = a.firstChild.getAttribute('class');
     if(cl == "icon-volume"){ 
      a.firstChild.setAttribute('class','icon-volume-off');
     }else{
      a.firstChild.setAttribute('class','icon-volume');
     } 
   };

See demo here



回答3:

WARNING: This is a (relatively) new attribute. Check the compatibility table from Mozilla's Developer Network before you proceed. If IE 9 (or below) is important to you, then this is not the answer you're looking for.

DOM elements have a property called classList. The 3 methods you should familiarize yourself with are add, remove, and toggle.

In your case:

var el = document.querySelector('i');
el.onclick = function () {
    el.classList.toggle('icon-volume');
    el.classList.toggle('icon-volume-off');
}

Pretty simple.