You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 08:36:05