[Bootstrap]讓Carousel元件能在手機上使用滑動手勢

在Bootstrap裡面有個方便的Carousel元件,可快速套用來輪播圖片,但這個元件在手機上並沒有支援滑動手勢,也就是在手機上左右滑動圖片是不會動的,在Bootstrap 3的時候,可以套用Jquery Mobile,然後加入類似以下jquery程式碼,就可以達到這個效過

$(document).ready(function() {
   $("#myCarousel").swiperight(function() {
      $(this).carousel('prev');
    });
   $("#myCarousel").swipeleft(function() {
      $(this).carousel('next');
   });
});

但是到了Bootstrap 4的時候,好像是因為4使用jquery 3的版本,跟Jquery Mobile不相容,而無法使用swiperight事件,所以我找到了一個不用加入Jquery Mobile外掛,就能達到效過的辦法,就是使用原生js的touch事件,加入以下code就可以了,非常好用

$(".carousel").on("touchstart", function(event){
        var xClick = event.originalEvent.touches[0].pageX;
    $(this).one("touchmove", function(event){
        var xMove = event.originalEvent.touches[0].pageX;
        if( Math.floor(xClick - xMove) > 5 ){
            $(this).carousel('next');
        }
        else if( Math.floor(xClick - xMove) < -5 ){
            $(this).carousel('prev');
        }
    });
    $(".carousel").on("touchend", function(){
            $(this).off("touchmove");
    });
});

以上都是在下面這網址找到的

https://stackoverflow.com/questions/21349984/how-to-make-bootstrap-carousel-slider-use-mobile-left-right-swipe

Leave a Reply

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *