js判斷手指的上滑,下滑,左滑,右滑,事件監聽

2022-05-14 20:57:56 字數 1190 閱讀 8385

原理:1:當開始乙個touchstart事件的時候,獲取此刻手指的橫座標startx和staery;

2:當觸發touchmove事件的時候,再獲取此時手指的橫座標moveendx和縱座標moveendy;最後,通過兩次獲取的座標差值來判斷手指在手機螢幕上的滑動方向。

**:$("body").on("touchstart", function(e) );

$("body").on("touchmove", function(e)

else if ( x < 0 )

else if ( y > 0)

else if ( y < 0 )

else

});總結:touchmove的最後座標減去touchstart的起始座標,x的結果如果正數,則說明手指是從左往右划動;x的結果如果負數,則說明手指是從右往左划動;y的結果如果正數,則說明手指是從上往下划動;y的結果如果負數,則說明手指是從下往上划動。

但是:實際上手指在手機上面滑動時很難做到直上直下的滑動;只要稍微有點斜,就會被x軸的判斷現行接管,而與我們的實際操作醫院相背離。此時就需要新增特殊的判斷技巧,**如下:

$("body").on("touchstart", function(e) );

$("body").on("touchmove", function(e)

else if ( math.abs(x) > math.abs(y) && x < 0 )

else if ( math.abs(y) > math.abs(x) && y > 0)

else if ( math.abs(y) > math.abs(x) && y < 0 )

else

});以上**,在測試時仍不能達到預期的效果,此時要注意到乙個事實--$('body').height = 0;

故還應該在此基礎上新增以下**:

var windowheight = $(window).height(),

$body = $("body");

// console.log($(window).height()); //627

// console.log($('body').height()); //0

$body.css("height", windowheight); //重要**

以上**結合在手機端就可以判斷手指的上滑,下滑,左滑,右滑操作;

參考文獻:

js判斷手指的上滑,下滑,左滑,右滑,事件監聽

原理 1 當開始乙個touchstart事件的時候,獲取此刻手指的橫座標startx和staery 2 當觸發touchmove事件的時候,再獲取此時手指的橫座標moveendx和縱座標moveendy 最後,通過兩次獲取的座標差值來判斷手指在手機螢幕上的滑動方向。body on touchstar...

js判斷手指的上滑,下滑,左滑,右滑,事件監聽

function touch else if startx else else if starty el.addeventlistener touchstart function e el.addeventlistener touchend function e touch 原理 1 當開始乙個to...

js判斷手指滑動方向(移動端)

varstartx,starty 獲得角度 function getangle angx,angy 根據起點終點返回方向 1向上 2向下 3向左 4向右 0未滑動 function getdirection startx,starty,endx,endy varangle getangle angx...