移動端之touch事件--手指的滑動事件

 轉自【B5教程網】:http://www.bcty365.com/content-142-5243-1.htmlcss

總結:touchmove的最後座標減去touchstart的起始座標。
X的結果若是正數,則說明手指是從左往右划動;
X的結果若是負數,則說明手指是從右往左划動;
Y的結果若是正數,則說明手指是從上往下划動;
Y的結果若是負數,則說明手指是從下往上划動。
轉自【B5教程網】:http://www.bcty365.com/content-142-5243-1.htmlhtml

 

 

代碼以下:
 
$("body").on("touchstart", function(e) { 
    e.preventDefault(); 
    startX = e.originalEvent.changedTouches[0].pageX, 
    startY = e.originalEvent.changedTouches[0].pageY; 
}); 
$("body").on("touchmove", function(e) { 
    e.preventDefault(); 
    moveEndX = e.originalEvent.changedTouches[0].pageX, 
    moveEndY = e.originalEvent.changedTouches[0].pageY, 
    X = moveEndX - startX, 
    Y = moveEndY - startY; 
       
    if ( Math.abs(X) > Math.abs(Y) && X > 0 ) { 
        alert("left 2 right"); 
    } 
    else if ( Math.abs(X) > Math.abs(Y) && X < 0 ) { 
        alert("right 2 left"); 
    } 
    else if ( Math.abs(Y) > Math.abs(X) && Y > 0) { 
        alert("top 2 bottom"); 
    } 
    else if ( Math.abs(Y) > Math.abs(X) && Y < 0 ) { 
        alert("bottom 2 top"); 
    } 
    else{ 
        alert("just touch"); 
    } 
}); 
以上代碼,在測試時仍不能達到預期的效果,此時要注意到一個事實--$('body').height = 0(此處是個大坑,但有時也不會出現,望大神指教)
故還應該在此基礎上添加一下代碼:
 
var windowHeight = $(window).height(), 
          $body = $("body"); 
      // console.log($(window).height()); 
      // console.log($('body').height()); 
      $body.css("height", windowHeight); 
到此,已實現了手機移動端手指的上滑、下滑、左滑和右滑操做。
轉自【B5教程網】:http://www.bcty365.com/content-142-5243-1.html測試

相關文章
相關標籤/搜索