简体   繁体   English

当前元素上的JavaScript切换类

[英]JavaScript toggle class on current element

Just want to understand a principle of JavaScript, I'm a bit new to this. 只想了解JavaScript的原理,对此我有点陌生。

I'm adding some styling to some element which are slides which I'm scrolling through. 我在某些元素中添加了一些样式,这些元素是我正在滚动浏览的幻灯片。

The "current" div have a transform: none applied, the two others get styled depending on where I am on the slider. “当前” div进行了transform: none应用transform: none ,另外两个则根据我在滑块上的位置进行样式设置。

I'm using this code which is working fine. 我正在使用此代码,它工作正常。

el.style.transform = i === e.current ? 'none' : i > e.current ? 'translateX(100%)' : 'translateX(-100%)'

My question is how do I add / toggle a class to the current el , and remove it back when it's not the current anymore. 我的问题是如何在当前el添加/切换class ,并在不再使用当前class将其删除。

I've tried some couple options using the same principle but can't find the right way to achieve it. 我已经尝试了使用相同原理的一些选项,但是找不到实现它的正确方法。

el.classList = i === e.current.toggle('classname') : i > ? e.current.toggle('classname')

el.classList.toggle() = i === e.current ? 'active' : i > e.current ? 'prev' : 'next'

Can somebody give me a heads up on how to achieve what i want to do? 有人可以提醒我如何实现我想做的事情吗? I've tried to go through some others post on Stack Overflow and to look on element.classList docs everywhere i could find it, but I'm stuck at this point and JS knowledge is not my strong point. 我试图遍历Stack Overflow上的其他文章,并在我能找到的所有地方查看element.classList文档,但是我被困在这一点上,而JS知识并不是我的强项。

Thanks! 谢谢!

toggle takes the class name eg el.classList.toggle('classname') . toggle具有类名称,例如el.classList.toggle('classname') You don't pass a variable to a function like this el.classList.toggle() = 'classname' . 您不会将变量传递给类似el.classList.toggle() = 'classname'的函数。 But you might be better off calling add or remove depending on if the item is the current one since you also need to ensure the other classes aren't still there. 但是您最好根据项目是否为当前项而调用addremove ,因为您还需要确保其他类还不存在。

el.classList[i === e.current ? 'add' : 'remove']('active');

However since you also want prev and next probably best not to try and be too clever with ternaries and make it readable: 但是,由于您还希望prevnext可能最好不要尝试对三元数太聪明并使其可读:

if (i > e.current) {
  el.classList.remove('current', 'prev');
  el.classList.add('next');
} else if (i < e.current) {
  el.classList.remove('current', 'next');
  el.classList.add('prev');
} else {
  el.classList.remove('prev', 'next');
  el.classList.add('current');
}

If you aren't worried about overwriting other classes you could simplify this using className as it overwrites any existing classes: 如果您不担心覆盖其他类,则可以使用className简化此过程,因为它会覆盖所有现有类:

if (i > e.current) {
  el.className = 'next';
} else if (i < e.current) {
  el.className = 'prev';
} else {
  el.className = 'current';
}

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

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