Toggle classname onclick JavaScript

后端 未结 5 1076
礼貌的吻别
礼貌的吻别 2020-12-16 03:06

I am nearly there, just a little unsure as to my code setup, I basically want to remove a class on click, and add it back again onclick, then remove onclick, then add onclic

5条回答
  •  旧时难觅i
    2020-12-16 03:58

    If you want to use a ternary operator, use this:

    document.getElementById('myButton').onclick = function() {
    
        var className = ' ' + myButton.className + ' ';
    
        this.className = ~className.indexOf(' active ') ?
                             className.replace(' active ', ' ') :
                             this.className + ' active';
    }
    

    For clarity, I'd use a regular if/else:

    document.getElementById('myButton').onclick = function() {
    
        var className = ' ' + myButton.className + ' ';
    
        if ( ~className.indexOf(' active ') ) {
            this.className = className.replace(' active ', ' ');
        } else {
            this.className += ' active';
        }              
    }
    

    Here's the fiddle: http://jsfiddle.net/ttEGY/

提交回复
热议问题