手机触屏事件

移动端触屏事件

移动端浏览器兼容较好,不需要考虑以前js的兼容问题,可以放心使用js书写效果
touch代表一个触摸点,触屏事件响应用户对屏幕或者触控板的操作

触摸touch事件 说明
touchstart 手指触控到一个dom元素触发
touchmove 手指在dom元素上滑动时触发
touchend 手指从DOM元素移开时触发
var body = document.body;
    var startX, startY, endX, endY;
    body.addEventListener("touchstart", function (e) {
        var touches = e.touches;
        startX = touches[0].pageX;
        startY = touches[0].pageY;

    });
    body.addEventListener("touchmove", function (e) {
        var touches = e.touches;
        endX = touches[0].pageX;
        endY = touches[0].pageY;
    });
触摸事件对象

TouchEvent是一类描述手指在触摸屏面的状态的变化的事件,这类事件用于描述一个或多个触点,使开发者可以检测触点的移动、触点的增加和减少
touchstart touchmove touchend 三个事件都会有各自事件对象

触摸列表 说明
touches 正在触摸屏的所有的手指的一个列表
targetTouches 正在触摸当前dom元素手指的一个列表
changeTouches 手指状态发生了改变的列表从无到有,从有到无的变化
  body.addEventListener("touchend", function (e) {
        //这个事件里面做最终的判断
        /*if (startX && endX) {
         if (endX - startX < 0) {
         console.log("左滑");
         }
         else {
         console.log("右滑");
         }
         startX = null;
         endX = null;
         }*/

        if (startX && startY && endX && endY) {
            var cx = endX - startX;
            var cy = endY - startY;
            if (Math.abs(cx) < Math.abs(cy) && cy < 0) {
                console.log("向上");
            }
            if (Math.abs(cx) < Math.abs(cy) && cy > 0) {
                console.log("向下");
            }
            if (Math.abs(cx) > Math.abs(cy) && cx < 0) {
                console.log("向左");
            }
            if (Math.abs(cx) > Math.abs(cy) && cx > 0) {
                console.log("向右");
            }
            startX=null;
            startY=null;
            endX=null;
            endY=null;
        }
    });

猜你喜欢

转载自blog.csdn.net/weixin_45955339/article/details/106948599