简体   繁体   English

仅当添加另一个类时,将类添加到元素

[英]Add class to an element, only when another class is added

I know this question could have similar duplicates but I can't find the solution. 我知道这个问题可能有相似的重复项,但找不到解决方案。 I have a slider with 3 slides. 我有一个带有3张幻灯片的滑块。 The plugin is the lightslider . 该插件是lightslider What I want to achieve is to fire a css animation to an element every time the 3rd slider is the current. 我要实现的是,每当第三个滑块为当前滑块时,将一个CSS动画触发到一个元素上。 I noticed that a class of active is being added to the current slide then, the this slide is the current-visible, like in the screenshot below. 我注意到当前正在向当前幻灯片添加一个active类别,该幻灯片是当前可见的,如下面的屏幕截图所示。

在此处输入图片说明

So my initial thought was the following. 所以我最初的想法是以下。 Grab the specific element ie svg-slide , check if the element has a class of active , and if yes, add the css class that fires the animation. 抓取特定元素,即svg-slide ,检查该元素是否具有active类,如果是,则添加触发动画的css类。

My code for that: 我的代码:

if ( $('.svg-slide').hasClass('active') ) {
   $('.svg-slide').addClass('fire-animation');
}

The problem with this one is, and correct me if I'm wrong, that when the page loads, the class of active is on the 1st slide, so the code has already checked that svg-slide doesn't have the active class and it does nothing afterwards. 这个问题是,如果我错了,请纠正我,即页面加载时, active类位于第一张幻灯片上,因此代码已检查svg-slide没有active类,并且之后它什么也不做。 Any help would be appreciated. 任何帮助,将不胜感激。

Why don't you use the getCurrentSlideCount method with onAfterSlide event? 为什么不将getCurrentSlideCount方法与onAfterSlide事件一起使用? And on change of the slide, if the current slide is the third slide you add the class you want: 在更改幻灯片时,如果当前幻灯片是第三张幻灯片,则添加所需的类:

 var yourSlider = $('#lightSlider').lightSlider({ loop:true, pauseOnHover: true, onAfterSlide: function (el) { var currentSlide = el.getCurrentSlideCount(); if(currentSlide == 3){ //add your class $('.active').addClass('TESTING'); } else { $('.active').removeClass('TESTING'); } } }); 

I've also made you a fiddle . 我也给你开了个小提琴

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

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