使用Splide.js结合animate.css实现轮播文本切换动画异常求助
问题根因
- 你的代码中使用
document.querySelector('.title')只会匹配DOM中第一个带有title类的元素,也就是第一张轮播图的标题,后续轮播切换时操作的始终是第一个标题元素,自然不会触发其他轮播页标题的动画。 - Splide的
active和inactive事件本身会传递当前触发事件的Slide实例参数,你没有接收该参数,就无法定位到当前轮播页下对应的标题元素。
修复方案
修改事件监听逻辑,从事件返回的Slide实例中获取当前轮播页的DOM节点,再在当前轮播页节点下查找标题元素即可:
document.addEventListener( 'DOMContentLoaded', function () { var splide = new Splide( '.slider', { type: 'fade', perPage: 1, autoplay: true, focus: 'center', trimSpace: false, rewind: true, } ).mount(); // 接收事件返回的slide参数 splide.on( 'active', function(slide) { // 在当前激活的slide节点下查找对应title元素 const element = slide.slide.querySelector('.title'); // 先移除再添加,同时触发重绘,保证每次切换都重新触发动画 element.classList.remove('animate__animated', 'animate__fadeInRight'); void element.offsetWidth; element.classList.add('animate__animated', 'animate__fadeInRight'); } ); splide.on( 'inactive', function(slide) { // 在当前失活的slide节点下查找对应title元素 const element = slide.slide.querySelector('.title'); element.classList.remove('animate__animated', 'animate__fadeInRight'); } ); });
内容的提问来源于stack exchange,提问作者Charis
相关产品推荐
相关产品推荐

