Swiper.js如何在滑动动画结束后为滑块添加自定义类?
实现方案
这个需求可以通过Swiper内置的slideChangeTransitionEnd事件实现,该事件会在滑动过渡动画完全结束、滑块进入静止状态后触发,刚好匹配你的使用场景。
改造后的JS代码
var mySwipper = new Swiper('.my-swiper', { slidesPerView: 3, slidesPerColumn: 2, spaceBetween: 30, slidesPerGroup: 3, speed: 800, autoplay: { delay: 3000 }, // 新增事件监听 on: { slideChangeTransitionEnd: function() { // 先清除所有滑块的自定义类 this.slides.removeClass('custom-active') // 给当前激活的滑块添加自定义类 this.slides.eq(this.activeIndex).addClass('custom-active') } } });
补充说明
slideChangeTransitionEnd事件对自动播放、手动拖拽滑动、点击切换等所有滑动场景都生效- 如果你的Swiper配置了多滑块同时激活(
slidesPerView大于1的场景),可以调整为给所有当前生效的激活滑块批量加自定义类,逻辑如下:
slideChangeTransitionEnd: function() { this.slides.removeClass('custom-active') this.slides.filter('.swiper-slide-active').addClass('custom-active') }
- 代码中的
custom-active可以替换为你需要的自定义类名。
内容的提问来源于stack exchange,提问作者user16714696
相关产品推荐
相关产品推荐

