本篇博客用於記錄使用swiper插件中的一些關鍵點:
首先附上官網地址:https://www.swiper.com.cn/
ios中使用swiper的坑:
/*解決swiper中蘋果點擊變暗,在css中加入下面這段*/ * { outline: none; webkit-focus-ring-color: rgba(0, 0, 0, 0); -webkit-tap-highlight-color: transparent; -webkit-touch-callout: none; -webkit-overflow-scrolling : touch; }
長屏滾動實現 填坑參考:
//這個swiper創建的是長屏滾動效果,重要的一點是,該對象的swiper-slide樣式的height要設為auto! var swiperObj = new Swiper ('.swiper-container', { direction: 'vertical', slidesPerView: 'auto', freeMode: true, mousewheelControl: true, roundLengths : true, on:{ touchMove: function(event){ }, touchEnd: function(event){ }, touchStart:function(event){ //this代表當前,如果頁面中有多個.swiper-container,則swiperObj為數組。 //swiperObj是個單獨對象時,this可以換成該對象名字 //下面兩行用來解決滑動過程中,點擊可停止。 this.setTransition(0) this.setTranslate(this.getTranslate()); }, transitionEnd: function(){ //下面的判斷通常用來監聽頁面箭頭提示,滑到底部隱藏 if(this.isEnd){ $('.arrowImg').hide(); }else{ $('.arrowImg').show(); } }, } })
初始化swiper時:如果該頁面是display等於none的狀態,那么在該頁面顯示時可以調用 swiper.update()方法激活,頁面寬高變化時,也可以調用update()來激活。
swiper做成長頁面滑動時,swiper.setTranslate(0)可以回到頂部。
跳轉到swiper中的某一屏:swiper.slideTo(index, speed, runCallbacks):
index | num | 必選 | 指定將要切換到的slide的索引 |
speed | num | 可選 | 切換速度(單位ms) |
runCallbacks | boolean | 可選 | 設置為false時不會觸發transition回調函數 |
swiper滾動條的設置:
注意:如果swiper里面有輸入框,彈起輸出法又彈下后滾動條位置不歸位,嘗試把滾動條的那個dom元素放到swiper-container元素之外,並且更新滾動條對應樣式。
<div class="swiper-scrollbar"></div>
.swiper-container-vertical>.swiper-scrollbar { position: absolute; right: 2%; top: 2%; z-index: 50; width: 2.8px; height: 100%; background-color: #616161; opacity: 0.7 !important; } .swiper-scrollbar-drag{ width: 100%; left: 0; background: rgba(255,255,255,0.6);
var swiperObj = new Swiper ('.swiperBox', { direction: 'vertical', scrollbar: { el: '.swiper-scrollbar', }, slidesPerView: 'auto', freeMode: true, mousewheelControl: true, roundLengths : true, on:{ touchMove: function(event){ }, touchEnd: function(event){ }, touchStart:function(event){ //this代表當前,如果頁面中有多個.swiper-container,則swiperObj為數組。 //swiperObj是個單獨對象時,this可以換成該對象名字 //下面兩行用來解決滑動過程中,點擊可停止。 this.setTransition(0) this.setTranslate(this.getTranslate()); } } })
最重要的是: 多查文檔 https://www.swiper.com.cn/api/index.html
注意:loop設為true的情況,可能會出現swiper中一些事件失效問題,索引也可能被打亂,這個要慎用。
loop為true解決參考:
loop為true代表可循環滾動,這時候插件就會創建若干個slide塊來補位讓滑動銜接,通常slide的數量就增多了。
部分slide塊中元素事件失效,也許是因為該塊slide是swiper復制補位的,但並未把事件帶過去,解決方法可以用標簽綁定。
<div onclick='method()'></div>,事件寫到標簽上,swiper復制出來的slide也擁有該事件屬性,slide中塊的索引和屬性,也可以寫在標簽上,data-index='1'。
this.activeIndex值出現變動,可以考慮用this.realIndex,結合實際的值去測試,也可以用數組索引去操作:
var slideArr = $('.swiper-slide');
slideArr[0].find('.obj').addClass('layer');