Vanilla [removed] Is there a way to toggle multiple CSS-classes in one statement?

后端 未结 9 1233
情深已故
情深已故 2021-01-02 07:50

I use these JavaScript-code to change classes in my script:

var toggleDirection = function() {
  group.classList.toggle(\'left-to-right\');
  group.classLis         


        
相关标签:
9条回答
  • 2021-01-02 07:56

    If I need to toggle multiple classes I just create an array and then iterate through it.

      var classes = [
        "red",
        "blue",
        "green",
        "purple"
      ]
    
      for (var i = 0; i < classes.length; i++){
        p.classList.toggle(classes[i])
      }
    
    
    0 讨论(0)
  • 2021-01-02 07:57

    You can extend the DOMTokenList object with the following multiToggle

    if (window["DOMTokenList"]) //check if DOMTokenList is an existing object.
    {
    //multitoggle
    DOMTokenList.prototype.multiToggle = function()
    {
        if (arguments.length > 0) // there needs to be at least one object
        {
            for (argument in arguments) //loop all arguments
            {
                var argument = arguments[argument];
                //All primitives are allowed as input (Symbol not included). If not a primitive, raise error.
                if (Object.prototype.toString.call(argument) !== "[object Undefined]" && Object.prototype.toString.call(argument) !== "[object Null]" && Object.prototype.toString.call(argument) !== "[object String]" && Object.prototype.toString.call(argument) !== "[object Number]" && Object.prototype.toString.call(argument) !== "[object Boolean]")   
                {
                    throw new SyntaxError;
                }
                else
                {
                    if (this.contains(argument)) //check if classList contains the argument.
                    {
                        this.remove(argument); //if so remove
                    }
                    else
                    {
                        this.add(argument); //if not add
                    }                   
                }
            }
        }
        else
        {
            throw new Error("The argument is not optional");
        }
        return undefined; //return undefined as with add and remove.
    }       
    }
    

    multiToggle does not have the force ability of the original toggle. It just turns class names on and off for as many arguments as supplied.

    Warning, expanding fixed Objects can cause troubles in the future . When an object gets deprecated or changed your functionality could break, requiring to more maintenance.

    0 讨论(0)
  • 2021-01-02 07:59

    Here is ES6 version of solution

    const classToggle = (el, ...args) => args.map(e => el.classList.toggle(e))
    

    const classToggle = (el, ...args) => {
      args.map(e => el.classList.toggle(e))
    }
    .a {
      color: red
    }
    
    .b {
      background: black
    }
    
    .c {
      border-color: yellow
    }
    <button onclick="classToggle(this,'a', 'c','b')" class="a b c ">Click me</button>

    And here's old JS code:

    var classToggle = function classToggle(el) {
      for (
        var _len = arguments.length,
          args = new Array(_len > 1 ? _len - 1 : 0),
          _key = 1;
        _key < _len;
        _key++
      ) {
        args[_key - 1] = arguments[_key];
      }
    
      args.map(function (e) {
        return el.classList.toggle(e);
      });
    };
    
    0 讨论(0)
  • 2021-01-02 08:07

    Assuming that myElement is a valid DOM Element, this works:

    ['right-to-left', 'left-to-right'].forEach(function(className){
      this.classList.toggle(className);
    }, myElement);
    
    0 讨论(0)
  • 2021-01-02 08:08

    just use the map array.

    like

    ['left-to-right', 'right-to-left'].map(v=> group.classList.toggle(v) )
    
    0 讨论(0)
  • 2021-01-02 08:10

    There is no direct way but you can create a helper function:

    const toggleClass =  (el, cls) => {
        if (Array.isArray(cls)) {
            cls.map((cl) => {
                el.classList.toggle(cl);
            });
        } else {
            el.classList.toggle(cls);
        }
    };
    
    

    Now just call toggleClass() like below:

    // single class
    toggleClass(document.querySelector('body'), 'left-to-right');
    //multiple classes
    toggleClass(document.querySelector('body'), ['left-to-right', 'right-to-left']);
    
    0 讨论(0)
提交回复
热议问题