有一個移動端的項目要求用jquery+bootstrap,其中有一個輪播圖,需求是要求可以手觸滑動,但是bootstrap中沒有寫手觸滑動的方法,自己琢磨着寫了出來,供大家參考。
$(function () { let $carousels = $('#carouselExampleSlidesOnly'); let start, // 初始值 end; // 結束值 $carousels.on('touchstart', function (e) { start = e.originalEvent.touches[0].clientX;// 觸摸開始時記錄一下手指所在的坐標x }); $carousels.on('touchmove', function (e) { end = e.originalEvent.touches[0].clientX;// 離開屏幕一瞬間的坐標x }); $carousels.on('touchend', function (e) { let distance = Math.abs(start - end); // 獲取差值 if (distance > 30) { //當差值大於30說明有方向的變化 $(this).carousel(start > end ? 'next' : 'prev'); //根據初始值和結束值的比較判斷向前滑還是向后滑 } }) })