How to toggle classes on click?

2019-03-06 23:48发布

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

3条回答
姐就是有狂的资本
2楼-- · 2019-03-06 23:55

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.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-03-06 23:57

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

查看更多
混吃等死
4楼-- · 2019-03-07 00:01

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');
    }
});
查看更多
登录 后发表回答