Toggle classname onclick JavaScript

后端 未结 5 1055
礼貌的吻别
礼貌的吻别 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条回答
  • 2020-12-16 03:35

    If JQuery is okay for you it really is as simple as

    $(myButton).toggleClass('active')
    

    http://jsfiddle.net/bikeshedder/eRJB4/

    0 讨论(0)
  • 2020-12-16 03:37

    Suggest common realization of toggleClass method:

    function toggleClass(element, tClass) {
        tClass = tClass.replace(/\s/g, "");
    
        var classes =  element.className;
        element.className = classes.indexOf(tClass) !== -1 
            ? classes.replace(" " + tClass, "")
            : classes + " " + tClass;
    }
    

    using:

    var element = document.getElementById('myId');
    toggleClass(element, 'active');
    
    0 讨论(0)
  • 2020-12-16 03:38

    I am really surprised nobody mentioned classList here. So just to be complete: Alternative solution would be to use classList method toggle().

    Your case would then simply be:

    document.getElementById('myButton').onclick = function() {
        this.classList.toggle('active');
    }
    

    e.classList.toggle() has good support (except for, ehm, IE, It's there since IE10). Click here for complete browser compatibility.

    0 讨论(0)
  • 2020-12-16 03:46

    Implementation using Array methods:

    const toggleClass = (element, className) => {
      let classNames = element.className.split(' ');
      let index = classNames.indexOf(className);
      if (index === -1) {
        classNames.push(className);
      } else {
        classNames.splice(index, 1);
      }
      element.className = classNames.filter(item => item !== '').join(' ');
    }
    

    Usage:

    let body = document.getElementsByTagName('body')[0];
    toggleClass(body, 'ready');
    

    Plunker

    0 讨论(0)
  • 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/

    0 讨论(0)
提交回复
热议问题