首页 > 解决方案 > 带有 animate.css 类的幻灯片之间的 Splide.js 文本动画

问题描述

我使用 splide.js 轮播,我想使用 animate.css 为幻灯片之间的文本标题设置动画。

我使用 splide 事件: https ://splidejs.com/guides/events/

这是我使用的代码:

document.addEventListener( 'DOMContentLoaded', function () {

  var splide = new Splide( '.slider', {
    type: 'fade',
    perPage: 1,
    autoplay: true,
    focus: 'center',
    trimSpace: false,
    rewind: true,

  } ).mount();

  splide.on( 'active', function() { 
    const element = document.querySelector('.title');
    element.classList.add('animate__animated', 'animate__fadeInRight');
    } );

  splide.on( 'inactive', function() {   
    const element = document.querySelector('.title');
    element.classList.remove('animate__animated', 'animate__fadeInRight');  
    } );

});

Codepen 示例: https ://codepen.io/haralake/pen/YzQObEK

第一张幻灯片得到了课程,但其他人没有。我想我以错误的方式使用事件,但我不知道问题出在哪里。

标签: javascriptcarouselanimate.csssplidejs

解决方案


我在自己的网站上使用 splide,这是我熟悉它的唯一原因,但他们的文档很糟糕。事件回调函数有一个事件对象,其中包含触发事件(例如变为活动或不活动)的幻灯片索引。是的,每次幻灯片更改时,活动事件都会运行,但请查看您正在查询的元素。无论什么是活动的,您都可以使用“title”类获取第一个元素。以下应该做你想要的。

splide.on( 'active', function(e) {  
    const element = document.querySelectorAll('.title');
    element[e.index].classList.add('animate__animated', 'animate__fadeInRight');
});

splide.on( 'inactive', function(e) {    
    const element = document.querySelectorAll('.title');
    element[e.index].classList.remove('animate__animated', 'animate__fadeInRight');  
});

推荐阅读