Bootstrap 自帶的 carousel 只有左右箭頭與指示點,在手机上少了最直覺的操作——滑。所幸只要引入一個手勢函式庫就能補上。
用 hammer.js 監聽輪播容器上的 swipeleft 與 swiperight,觸發時呼叫 Bootstrap carousel 既有的 next 與 prev 方法即可。CDN 很多,例如 //cdn.bootcss.com/hammer.js/2.0.8/hammer.min.js,在 head 中引入。
<div data-ride="carousel" class="carousel slide" id="carousel-example-generic"> <ol class="carousel-indicators"> <li class="" data-slide-to="0" data-target="#carousel-example-generic"></li> <li data-slide-to="1" data-target="#carousel-example-generic" class="active"></li> <li data-slide-to="2" data-target="#carousel-example-generic" class=""></li> </ol> <div role="listbox" class="carousel-inner"> <div class="item"> <img alt="First slide" src="https://ibootstrap-file.b0.upaiyun.com/lorempixel.com/1600/500/sports/1/default.jpg" data-holder-rendered="true"> </div> <div class="item active"> <img alt="Second slide [1140x500]" src="https://ibootstrap-file.b0.upaiyun.com/lorempixel.com/1600/500/sports/2/default.jpg" data-holder-rendered="true"> </div> <div class="item"> <img alt="Third slide [1140x500]" src="https://ibootstrap-file.b0.upaiyun.com/lorempixel.com/1600/500/sports/3/default.jpg" data-holder-rendered="true"> </div> </div> <a data-slide="prev" role="button" href="#carousel-example-generic" class="left carousel-control"> <span aria-hidden="true" class="glyphicon glyphicon-chevron-left"></span> <span class="sr-only">Previous</span> </a> <a data-slide="next" role="button" href="#carousel-example-generic" class="right carousel-control"> <span aria-hidden="true" class="glyphicon glyphicon-chevron-right"></span> <span class="sr-only">Next</span> </a> </div>
<script>
$(function(){
var myElement = document.getElementById('carousel-example-generic');
var hm = new Hammer(myElement);
hm.on("swipeleft", function(){
$('#carousel-example-generic').carousel('next');
});
hm.on("swiperight", function(){
$('#carousel-example-generic').carousel('prev');
});
})
</script>
id 必須對得上。getElementById 抓的那個 id 要和 markup 上的 id="carousel-example-generic" 完全一致,否則手勢綁不到任何元素,滑了也沒反應。
jQuery 版本會影響手機上的表現。實測在 jQuery 1.9.x(如 jquery-1.9.1.min.js)下比較穩定;版本過新時可能出現「電腦上滑得動、手機上摸不到」的狀況,遇到時先回頭檢查 jQuery 版本。
如果不想額外引入函式庫,也可以自己監聽 touchstart 與 touchend,比對兩次 changedTouches[0].pageX 的差值與位移時間,自行判定左右滑——邏輯不難,只是邊界條件要自己處理乾淨。