2016-04-11 69 views
0

我使用这些JavaScript代码来改变我的脚本类:香草JavaScript:有没有办法在一个语句中切换多个CSS类?

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

在我的例子有一个只有两班改变,但可能是还多类...

因此,因此:有没有人知道一个写少量多余的例子的方法?

+0

您可以为'Element' =>创建自己的原型https://jsfiddle.net/rayon_1990/2noyz7zf/ – Rayon

回答

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); 
     } 
    ); 
} 
1

没有直接使用Element.classList API是不可能的。看看API你可以阅读:

toggle(String [,force])当只有一个参数时:切换 class value;即如果类存在,则将其删除,如果不存在,则添加 它。当第二个参数存在:如果第二个参数是真实的, 添加指定的类值,如果是假的,将其删除。

Reference here

你可能会写自己的“效用”功能(在香草JS),这你想要做什么,很简单的示范例子,低于该工作在classList API之上:

var superToggle = function(element, class0, class1) { 
    element.classList.toggle(class0); 
    element.classList.toggle(class1); 
} 

你打电话它以这种方式:

superToggle(group,'left-to-right', 'right-to-left'); 
1

您可以通过以下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延长DOMTokenList对象不具有原始toggleforce能力。它只是将类名打开和关闭,以获得尽可能多的参数。

警告,扩大固定物体可引起后患。当一个对象被弃用或改变时,你的功能可能会中断,需要更多的维护。

相关问题