我正在通过一个数组来根据外部设置的状态应用不同的类。这就是我现在的做法,但我觉得我在重复自己很多次。有干燥机的方法吗?如果有帮助,类名可以是其他名称。
var children2 = Array.from(wrapper.children);
var s = state.state;
children2.forEach((child, i) => {
var classes = [];
child.classList.remove('active', 'before', 'previous', 'next', 'after');
if(i < s) { classes.push('before'); };
if(i > s) { classes.push('after'); };
if(i === s) { classes.push('active') }
if(i === s - 1) { classes.push('previous') }
if (i === s + 1) { classes.push('next') }
child.classList.add(...classes)
})
请您参考如下方法:
最简单的解决方案是使用 toggle
:
toggle( String [, force] )
When only one argument is present: Toggle class value; i.e., if class exists then remove it and return false, if not, then add it and return true.
When a second argument is present: If the second argument evaluates to true, add specified class value, and if it evaluates to false, remove it.
例如像这样:
let classes = child.classList;
classes.toggle('before', i < s);
classes.toggle('after', i > s);
classes.toggle('active', i === s);
classes.toggle('previous', i === s-1);
classes.toggle('next', i === s+1);
您还可以使用键和条件创建一个对象,然后循环遍历它以分别切换
它们:
const classes = {
before: i < s,
after: i > s,
active: i === s,
previous: i === s - 1,
next: i === s + 1,
};
Object.entries(classes).forEach(([className, condition]) => child.classList.toggle(className, condition));
(注意 Object.entries
是 ECMAScript 2017 的一个特性。)