简体   繁体   English

根据条件添加或删除类

[英]Add or remove a class based on a condition

I am adding / removing a class from an element's classList based on a variable's truthiness.我正在根据变量的真实性从元素的classList添加/删除一个类。 However, I'm doing it in what appears to be an obtuse way:但是,我正在以一种看似迟钝的方式进行操作:

if (myConditionIsMet) {
  myEl.classList.add("myClass");
} else {
  myEl.classList.remove("myClass");
}

Is there a way in which I could make this more sexy and dynamically call the add / remove chained function for example with a conditional operator such as:有没有一种方法可以让我更性感并动态调用add / remove链接函数,例如使用条件运算符,例如:

myEl.classList.{myConditionIsMet ? add('myClass') : remove('myClass')};

The above is pseudocode, of course, and I would like as plain JS as possible.当然,上面是伪代码,我希望尽可能简单的JS。

Your pseudocode js你的伪代码js

myEl.classList.{myConditionIsMet ? add('myClass') : remove('myClass')};

can be translated to actual js可以翻译成实际的js

myEl.classList[myConditionIsMet ? 'add' : 'remove']('myClass');

which is not particularly readable, but does exactly what you described.这不是特别可读,但完全符合您的描述。

For readability, I would look at the toggle method.为了可读性,我会看一下toggle方法。

There's a toggle method on .classList which takes a second argument ( force ). .classList上有一个toggle方法,它采用第二个参数( force )。 This boolean argument essentially takes a condition that adds the class if true, and removes the class if false.这个布尔参数本质上采用一个条件,如果为真则添加类,如果为假则删除类。

myEl.classList.toggle("myClass", myConditionIsMet);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM