js實現簡易的touch事件(es5)

白木_洋發表於2019-03-02
    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);
    }
複製程式碼

相關文章