移動端滑動方向判斷

來源:互聯網
上載者:User

標籤:utf-8   height   就是   1.0   ack   eve   AC   fun   poi   

移動端滑動方向判斷,主要是判斷利用x,y軸方向的增量,哪個軸增的快,就是哪個方向。

在touchstart中擷取初始點,startX, startY; 

在touchmove中擷取移動點,moveX, moveY

計算兩者的差 deltaX = moveX - startX;  deltaY = moveY - startY;

之後累加deltaX和deltaY:

distX += Math.abs(deltaX)
distY += Math.abs(deltaY)

if (distX > distY && deltaX > 0) {
console.log(‘右滑‘)
}
if (distX > distY && deltaX < 0) {
console.log(‘左滑‘)
}
if (distX < distY && deltaY < 0) {
console.log(‘上滑‘)
}
if (distX < distY && deltaY > 0) {
console.log(‘下滑‘)
}

思路就是這樣,代碼如下

<!DOCTYPE html><html>  <head>    <meta charset="utf-8">    <meta name="viewport" content="width=device-width,initial-scale=1.0">    <title>滑動方向判斷</title>    <style>     #box{      width: 100%;      height: 500px;      background: orange;     }    </style>  </head>  <body>    <div id="box"></div>    <script>      let startX,startY,moveX,moveY,deltaX,deltaY;      let distX = 0      let distY = 0      let box = document.getElementById(‘box‘)      box.addEventListener(‘touchstart‘, function(e) {          let point = e.touches ? e.touches[0] : e          startX = point.pageX          startY = point.pageY          distX = 0          distY = 0      })      box.addEventListener(‘touchmove‘, function(e) {          let point = e.touches ? e.touches[0] : e          moveX = point.pageX          moveY = point.pageY          deltaX = moveX - startX          deltaY = moveY - startY          distX += Math.abs(deltaX)          distY +=  Math.abs(deltaY)          console.log(distX, distY)          if (distX > distY && deltaX > 0) {            console.log(‘右滑‘)          }           if (distX > distY && deltaX < 0) {            console.log(‘左滑‘)          }          if (distX < distY && deltaY < 0) {            console.log(‘上滑‘)          }           if (distX < distY && deltaY > 0) {            console.log(‘下滑‘)          }      })    </script>  </body></html>

 

移動端滑動方向判斷

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.