js实现简易的touch事件(es5)

    var btn = document.querySelector('#btn');
    btn.ontouchstart = function (e) {
        var point = e.changedTouches[0];
        this.strX = point.pageX;
        this.strY = point.pageY;
        this.isMove = false;
    }
    btn.ontouchmove = function (e) {
        var point = e.changedTouches[0];
        //手指按下去或多或少都会有滑动。一般以10像素为偏差值
        var chengeX = point.pageX - this.strX,
            chengeY = point.pageY - this.strY;
        this.chengeX = chengeX;
        this.chengeY = chengeY;
        if(Math.abs(chengeX) > 10 || Math.abs(chengeY) > 10){
            this.isMove = true;
        }
    }
    btn.ontouchend = function (e) {
        var point = e.changedTouches[0];
        if(!this.isMove) {
            console.log('我是点击操作--');
            return;
        }
        var dir = null;
        if(Math.abs(this.chengeX)> Math.abs(this.chengeY)) {
            dir = this.chengeX < 0 ? 'left' : 'right';
        }else {
            dir = this.chengeY < 0 ? 'up' : 'down';
        }
        console.log(dir);
    }
复制代码

转载于:https://juejin.im/post/5c791c4f6fb9a049b07e0f63

你可能感兴趣的:(js实现简易的touch事件(es5))