纯JavaScript:有没有一种方法可以在一个语句中切换多个CSS类?

36

我使用以下 JavaScript 代码来在我的脚本中改变类:

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

在我的例子中,只有两个类需要更改,但也可能有多个类需要更改...

因此,有人知道如何以更少的冗余方式编写示例吗?


你可以为 Element 创建自己的原型 => https://jsfiddle.net/rayon_1990/2noyz7zf/ - Rayon
是的!可以用逗号分隔或使用展开语法中的数组,答案下面有示例这里 - Jeff Spicoli
12个回答

1
你可以使用以下的 multiToggle 扩展 DOMTokenList 对象。
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没有原始的toggleforce能力。它只是为提供的参数打开和关闭类名。

警告:扩展固定对象可能会在未来造成问题。当一个对象被弃用或更改时,您的功能可能会中断,需要进行更多的维护。


0

以下代码应该可以正常工作;前提是这些类名在你的CSS中已经定义,并且当前页面上的一些元素具有这些类名:

var toggleDirection = function()
{
    var ltr, rtl, lst, cls;

    ltr = 'left-to-right';
    rtl = 'right-to-left';
    lst = [].slice.call(document.getElementsByClassName(ltr));

    lst = ((lst.length > 0) ? lst : [].slice.call(document.getElementsByClassName(rtl)));

    lst.forEach
    (
        function(node)
        {
            cls = node.getAttribute('class');

            if (cls.indexOf(ltr) > -1)
            { cls.split(ltr).join(rtl); }
            else
            { cls.split(rtl).join(ltr); }

            node.setAttribute('class', cls);
        }
    );
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接