移動端屏幕空間有限,輪播圖是承載多張圖片的常用方案,同時還得考慮用戶流量成本。多方比較之後,個人覺得 swipe.js 是一個相當趁手的選擇。
它是純 JavaScript 實現,不需要搭配其他 JS 庫,同時兼容 jQuery 與 zepto,壓縮後僅約 6KB,非常適合移動端場景。項目地址:https://github.com/thebird/swipe
官方文檔寫得很清楚,結構與樣式如下:
<div id='slider' class='swipe'>
<div class='swipe-wrap'>
<div></div>
<div></div>
<div></div>
</div>
</div>
.swipe { overflow: hidden; visibility: hidden; position: relative; }
.swipe-wrap { overflow: hidden; position: relative; }
.swipe-wrap > div { float:left; width:100%; position: relative; }
初始化只有一行:
window.mySwipe = Swipe(document.getElementById('slider'), opt);
.swipe 嵌套 .swipe-wrap 這層結構最好不要改動,最內層的 div 可以換成 li 等其他標籤。
prev():上一幀;next():下一幀getPos():當前索引;getNumSlides():總幀數slide(index, duration):跳到指定幀實際項目裡,banner 上通常還要加指示器並配置參數,寫法如下:
<div class="banner">
<div id="slider" class="swipe">
<ul class="swipe-wrap">
<li><a href="javascript:void(0)"><img src="img/1.jpg"></a></li>
<li><a href="javascript:void(0)"><img src="img/2.jpg"></a></li>
<li><a href="javascript:void(0)"><img src="img/3.jpg"></a></li>
<li><a href="javascript:void(0)"><img src="img/4.jpg"></a></li>
<li><a href="javascript:void(0)"><img src="img/5.jpg"></a></li>
</ul>
<ul class="slide-trigger">
<li class="cur"></li><li></li><li></li><li></li><li></li>
</ul>
</div>
</div>
.banner { width: 100%; position: relative; }
.banner .swipe { overflow: hidden; position: relative; }
.banner .swipe-wrap { overflow: hidden; position: relative; list-style: none; }
.banner .swipe-wrap li { float: left; position: relative; }
.banner img { width: 100%; vertical-align: middle; }
.banner .slide-trigger {
position: absolute; left: 0; bottom: 0; width: 100%; z-index: 10;
display: flex; justify-content: center; list-style: none;
}
.banner .slide-trigger li {
width: 10px; height: 10px; background: #FFF; margin: 5px; border-radius: 50%;
}
.banner .slide-trigger .cur { background: #2fc7c9; }
var slider = $('#slider');
slider.find(".slide-trigger").find("li").eq(0).addClass("cur");
window.mySwipe = new Swipe(document.getElementById('slider'), {
speed: 400,
auto: 3000,
callback: function(index, elem) {
slider.find(".slide-trigger").find("li").eq(index).addClass("cur").siblings().removeClass("cur");
}
});
指示器的高亮完全靠 callback 裡拿到的 index 來同步,這也是自定義輪播控件最常見的做法。
在看 zepto 源碼與事件時發現一個現象:
$('body').swipeUp(function(e){ alert('swipeUp'); // 偶爾有效 })
$('body').swipeDown(function(e){ alert('swipeDown'); // 偶爾有效 })
$('body').tap(function(){ alert('tap'); }) // 正常
$('body').swipeLeft(function(){ alert('swipeLeft'); }) // 正常
$('body').swipeRight(function(){ alert('swipeRight'); }) // 正常
左右滑動和 tap 都正常,唯獨上下滑動時靈時不靈。原因有兩個方向:
方案一:補充引入 touch 模塊。zepto 的 touch 事件能力需要顯式加載 touch.js 模塊,官網下載的版本裡並不包含,需要去 GitHub 單獨取文件後引入。
方案二:阻止瀏覽器默認的頁面下拉/回彈行為。加上這段代碼即可:
document.addEventListener('touchmove', function (event) {
event.preventDefault();
}, false);
瀏覽器本身要處理垂直方向的滾動與下拉手勢,會把垂直位移吃掉,导致 swipeUp/swipeDown 判定不穩定;攔住 touchmove 的默認行為後,垂直滑動事件就能被正常分發。實踐中建議只針對輪播區域而非整個 document 做攔截,以免影響頁面正常滾動。