如何在幻灯片到达末尾时将 class 添加到 swiper.js 中的容器?
How to add a class to the container in swiper.js when slide has reached the end?
我正在为一个特定的项目使用 swiper.js,在大多数情况下它没问题。但是我想根据幻灯片处于开头、中间或结尾的时间来调整容器的外观。
我知道有一个事件要监视它,但我不知道如何将 class 添加到触发该特定事件的容器 DOM,因为在同一页。我尝试使用 this.addClass('reached-end')
和 $(this).addClass('reached-end')
,但没有用。
<div class="carousel-container">
<div class="swiper-wrapper">
<div class="swiper-slide">First Slide</div>
<div class="swiper-slide">Last Slide</div>
</div>
</div>
var cardDeck = new Swiper('.carousel-container', {
on: {
reachEnd: function () {
//add .reached-end to .carousel-container
// $(this).addClass('reached-end') // this didn't work
// this.addClass('reached-end') // this didn't work either
}
}
});
从documentation你可以看到所有事件运行在Swiper实例的范围内,而不是你的代码所期望的容器元素:
Please note, that this keyword within event handler always points to Swiper instance
因此,您需要 select 事件处理程序中的元素。请注意,Swiper 为此提供 $el
和 $wrapperEl
属性,具体取决于您要定位的父对象。
var cardDeck = new Swiper('.carousel-container', {
on: {
reachEnd: function () {
this.$el.addClass('reached-end');
}
}
});
我正在为一个特定的项目使用 swiper.js,在大多数情况下它没问题。但是我想根据幻灯片处于开头、中间或结尾的时间来调整容器的外观。
我知道有一个事件要监视它,但我不知道如何将 class 添加到触发该特定事件的容器 DOM,因为在同一页。我尝试使用 this.addClass('reached-end')
和 $(this).addClass('reached-end')
,但没有用。
<div class="carousel-container">
<div class="swiper-wrapper">
<div class="swiper-slide">First Slide</div>
<div class="swiper-slide">Last Slide</div>
</div>
</div>
var cardDeck = new Swiper('.carousel-container', {
on: {
reachEnd: function () {
//add .reached-end to .carousel-container
// $(this).addClass('reached-end') // this didn't work
// this.addClass('reached-end') // this didn't work either
}
}
});
从documentation你可以看到所有事件运行在Swiper实例的范围内,而不是你的代码所期望的容器元素:
Please note, that this keyword within event handler always points to Swiper instance
因此,您需要 select 事件处理程序中的元素。请注意,Swiper 为此提供 $el
和 $wrapperEl
属性,具体取决于您要定位的父对象。
var cardDeck = new Swiper('.carousel-container', {
on: {
reachEnd: function () {
this.$el.addClass('reached-end');
}
}
});