同一個問題,換一套解法。除了 hammer.js,也可以使用輕量的 toucher.js(專案位在 GitHub 的 bh-lay/toucher),它對 event 的命名更接近底層觸摸事件,也更貼近「點一下左右箭頭」的直覺。
<script type="text/JavaScript" src="__PUBLIC__/home/js/toucher.js"></script>
這裡刻意幫左右兩個控制項加上 id="carleft" 與 id="carright",方便稍後用程式觸發。
<div id="carousel-example-generic" class="carousel slide both" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li> <li data-target="#carousel-example-generic" data-slide-to="1"></li> <li data-target="#carousel-example-generic" data-slide-to="2"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner" role="listbox"> <div class="item active"> <img src="__PUBLIC__/home/img/banner_01.jpg" alt="..."> <div class="carousel-caption"> ... </div> </div> <div class="item"> <img src="__PUBLIC__/home/img/banner_02.jpg" alt="..."> <div class="carousel-caption"> ... </div> </div> <div class="item"> <img src="__PUBLIC__/home/img/banner_03.jpg" alt="..."> <div class="carousel-caption"> ... </div> </div> </div> <!-- Controls --> <a id="carleft" class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a id="carright" class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next"> <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div>
<script>
var myTouch = util.toucher(document.getElementById('carousel-example-generic'));
myTouch.on('swipeLeft', function(e){
$('#carright').click();
}).on('swipeRight', function(e){
$('#carleft').click();
});
</script>
它沒有直接呼叫 carousel('next'),而是觸發既有箭頭的 click。這樣做的好處是:箭頭上原本綁定的行為(例如邊界判斷、指示點同步、自訂回呼)全都會照常執行,不必重複實作一次,日後改箭頭邏輯也不用同步改兩處。
要留意的是事件名稱的-style差異:toucher.js 用的是駝峰式 swipeLeft / swipeRight,hammer.js 則是全小寫的 swipeleft / swiperight,兩者不能混用。
另外 util.toucher 需要掛在已存在的 DOM 元素上,因此這段程式碼要放在元素之後或包在 DOMContentLoaded 裡,否則會抓到 null。