-
只对触摸手势起作用,不能鼠标控制
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>滑动手势</title> <style type="text/css"> .box{ width:300px; height:300px; background-color: pink; } </style> </head> <body> <div class="box"></div> <script> window.onload = function(){ var bindSwipeEvent = function(dom, leftSwipeCallback, rightSwipeCallback){ var isMove = false; //是否位移 var startX = 0; //起始位置 var moveX = 0; //移动距离,距离大于50px认为是滑动 dom.addEventListener("touchstart", function(e){ startX = e.touches[0].clientX; }); dom.addEventListener("touchmove", function(e){ isMove = true; moveX = e.touches[0].clientX - startX; }); dom.addEventListener("touchend", function(e){ if(isMove && Math.abs(moveX) > 50){ if(moveX < 0){ leftSwipeCallback && leftSwipeCallback.call(this, e); }else{ rightSwipeCallback && rightSwipeCallback.call(this, e); } } //重置变量 isMove = false; startX = 0; moveX = 0; }); } bindSwipeEvent(document.querySelector(".box"), function(e){ console.log("左滑动"); console.log(this); console.log(e); }, function(e){ console.log("右滑动"); console.log(this); console.log(e); }); } </script> </body> </html>
3.js移动端滑动手势
最新推荐文章于 2024-07-25 14:57:57 发布