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