问题
I am trying to target the active slide
in my slick carousel
by ken wheeler to add an animation to the p element within that slide.
So, when the slide
is active, the p
element will bounce in (or something), then when the slide transitions to the next slide, the animation will be applied to the new p element. After the slides have looped, the animated class will be continuously applied to the slick carousel
.
HTML:
<div class="slick-promo">
<div class="single-slide">[img code here]<p>This text will come in animated, then as the slide leaves it will have the animation class removed.</p></div>
<div class="single-slide">[img code here]<p>Lorem ipsum blah blah</p></div>
<div class="single-slide">[img code here]<p>lorem ipsum blah blah</p></div>
</div>
The images
and several classes
are dynamically generated by other programs I use.
Javascript:
jQuery(document).ready(function($){
$('.slick-promo').slick({
infinite: true,
fade: true,
cssEase: 'linear',
slidesToShow: 1,
slidesToScroll: 1,
autoplay: true,
autoplaySpeed: 2000,
//this is where I need help
onAfterChange:function(slider,index){
$('.slick-active p').toggleClass('animated bounce');
}
});
});
The .slick-active
class is dynamically generated by the slick carousel
. I am targeting the p
element in the above HTML code. The animated bounce
classes are tied to css that generate the animation.
I am very new to Javascript/jQuery
, so my mistake could be elementary. I have searched the web for many hours now trying to find out what I need to do...
回答1:
The issue was in how classes were added and deleted during the afterChange and beforeChange events provided by the slick carousel.
Javascript:
$('.slick-promo').on('afterChange', function(event, slick, currentSlide){
$('.slick-active p').removeClass('hidden');
$('.slick-active p').addClass('animated bounce');
});
$('.slick-promo').on('beforeChange', function(event, slick, currentSlide){
$('.slick-active p').removeClass('animated bounce');
$('.slick-active p').addClass('hidden');
});
By doing this, I was able to add the .hidden class to my p elements on the html. Now I've successfully targeted my elements when slides are changed in and out, which makes for smoother animation.
Please note, this caused the first slide to have an error upon load. My workaround is to have the hidden class not on the first slide...
来源:https://stackoverflow.com/questions/29544055/slick-carousel-target-active-slide-to-add-and-remove-animation-classes