手势事件
会听过什么左滑喜欢,右滑不喜欢,那么这样的滑动手势如何实现,在此用touch事件来实现左右滑动的判断
左右滑动
<!DOCTYPE html> <html lang="en">
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <title>Title</title> <style> body { margin: 0; padding: 0; }
.box { width: 200px; height: 200px; background: pink; float: left; } </style> </head>
<body> <div class="box"></div> <script> window.onload = function () {
var bindSwipeEvent = function (dom, leftCallback, rightCallback) { var isMove = false; var startX = 0; var distanceX = 0; dom.addEventListener('touchstart', function (e) { startX = e.touches[0].clientX; }); dom.addEventListener('touchmove', function (e) { isMove = true; var moveX = e.touches[0].clientX; distanceX = moveX - startX; }); dom.addEventListener('touchend', function (e) { if (isMove && Math.abs(distanceX) > 50) { if (distanceX > 0) { rightCallback && rightCallback.call(this, e); } else { leftCallback && leftCallback.call(this, e); } } isMove = false; startX = 0; distanceX = 0; }); } bindSwipeEvent(document.querySelector('.box'), function (e) { console.log(e); console.log('左滑手势'); }, function (e) { console.log(e); console.log('右滑手势'); });
} </script> </body>
</html>
|
注意:
rightCallback && rightCallback.call(this, e);
|
前面一个表示判断是否有传入该方法,后面表示调用,但是必须先确保有传入,才能调用