swiper实现无缝轮播 中间显示主图 两边显示部分


版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_41544124/article/details/85794561
现在有很多轮播的效果都是中间显示主图,两边显示部分图片的效果,用swiper实现其实很容易,先上效果图

css实时很简单

给swiper-wrapper宽度设置成100%;swiper-slide设置成80%就可以两边显示部分了

html

<div id="slide">
<div className="swiper-container">
<div className="swiper-wrapper">
{
list.map((item, index) =>
<div className="swiper-slide">
<div className="div">
<ImportedImage img={item.pic}></ImportedImage>
<div className="title">{item.title}</div>
<ul className="content">
{
item.text.map((o, i) =>
<li>· {o}</li>
)
}
</ul>
</div>
<div className="icon" data-type="add" data-id={item.id}></div>
</div>
)
}
</div>
<div className="swiper-pagination">
</div>
</div>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
js 这里用的是swiper4 点击回调和swiper3还是有区别的
swiper3和swiper4的区别


另外这块实现的功能是点击+进行添加 点击整个slide进行跳转
swiper 默认是阻止事件冒泡的 (preventClicksPropagation:true)


var mySwiper = new Swiper ('.swiper-container', {
direction: 'horizontal',
loop: true,
slidesPerView: "auto",
centeredSlides:true,
spaceBetween: 20,
如果需要分页器
pagination: {
el: '.swiper-pagination'
},
on: {
click: (event) => {
const index = mySwiper.activeIndex % list.length;
const type = event.target.getAttribute("data-type");
const id = event.target.getAttribute("data-id");
if (type == 'add') {
t.onBtnAdd(id);
} else {
window.location.href = list[index].url;
}
}
},

})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
最后总结踩坑

当swiper设置了 loop:true 的时候,点击事件直接绑定在元素上 ,部分 slide的点击事件有时会失效。

导致的原因

当loop模式下slides前后会clone若干个slide,从而形成一个环路,但是却不会复制绑定在dom上的click事件

解决

不要将click事件绑定在dom上,而是在new Swiper()中的on回调函数中统一调用
————————————————
版权声明:本文为CSDN博主「继续向前~」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_41544124/article/details/85794561


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM