美文网首页让前端飞
swiper获取当前页索引值与内容|swiper教程

swiper获取当前页索引值与内容|swiper教程

作者: 木易早上 | 来源:发表于2019-05-11 20:06 被阅读0次

当我们swiper左右滑动页面的时候,需要获取swiper active当前页的索引值或者内容,在swiper3.4.2等旧版和现在的swiper4.0.1等新版是不一样的,要分开进行学习,主要是slideChange事件不一样。

html内容如下,例如。

<div class="swiper-container"> 

<!-- 添加一个slide -->  

<div class="swiper-wrapper">   

<!-- Slides -->   

<div class="swiper-slide">Slide 1<img src="xxxx.png"></div>   

<div class="swiper-slide">Slide 2</div>   

<div class="swiper-slide">Slide 3</div>  

</div>

</div>

当我们用swiper滑动界面的时候,我们需要获取当前active页面的索引值与内容,也可以获取下面标签的内容,例如img标签,索引值从0开始计数,先看看swiper旧版的实现方式。

//初始化

var mySwiper = new Swiper ('.swiper-container', {  

direction: 'horizontal',

 loop: false,    

//主要看以下部分  

onSlideChangeEnd : function(swiperHere) {   

//获取下面的img图片   

var imgurl = $('.swiper-slide-active img').attr("src");   

//获取内容文本   var txt = $('.swiper-slide-active').html();   

console.log("内容:"+txt+"===索引值:"+swiperHere.activeIndex+"===图片地址:"+imgurl);  

}

})

swiper4.0.1新版的slideChange事件有点不一样,使用了“on”来绑定事件,如下。

//初始化

var mySwiper = new Swiper ('.swiper-container', {  

 direction: 'horizontal',

 loop: false

})

//主要是这部分

mySwiper.on('slideChangeTransitionEnd', function () {

 var imgurl = $('.swiper-slide-active img').attr("src");  

var txt = $('.swiper-slide-active').html();  

console.log("内容:"+txt+"===索引值:"+mySwiper.activeIndex+"===图片地址:"+imgurl);

});

转载自:http://www.tpyyes.com/a/html5/2017/1026/325.html

相关文章

网友评论

    本文标题:swiper获取当前页索引值与内容|swiper教程

    本文链接:https://www.haomeiwen.com/subject/pbjfaqtx.html