移动端手势事件及长按事件模拟

H5原生事件中为移动端增加了3个触控事件,touchstart、touchmove、touchend;但是我们在实际使用手机时有长按和手势动作,但是原生并没有给我们封装类似的事件,所以我们需要模拟实现。

(function () {
    const touch = new Event("touch"),
        longTop = new Event("longTop"),
        swipeLeft = new Event("swipeLeft"),
        swipeRight = new Event("swipeRight"),
        swipeBottom = new Event("swipeBottom"),
        swipeTop = new Event("swipeTop");
    var eventStart, eventEnd, eventX, eventY, diffX, diffY, changeNum;
    document.addEventListener("touchstart", function (e) {
        eventStart = e.timeStamp;
        eventX = e.targetTouches[0].screenX;
        eventY = e.targetTouches[0].screenY
    });
    document.addEventListener("touchmove", function (e) {
        //手势改变的数据必须在move阶段才能获取,并计算出手势方向
        diffX = e.targetTouches[0].screenX - eventX;
        diffY = e.targetTouches[0].screenY - eventY;
        changeNum = Math.abs(diffX) - Math.abs(diffY)
    });
    document.addEventListener("touchend", function (e) {
        if (diffX && diffY && changeNum) {
            if (changeNum > 0) {
                if (diffX > 0) {
                    e.target.dispatchEvent(swipeRight)
                } else {
                    e.target.dispatchEvent(swipeLeft)
                }
            } else {
                if (diffY < 0) {
                    e.target.dispatchEvent(swipeTop)
                } else {
                    e.target.dispatchEvent(swipeBottom)
                }
            }
        } else {
            eventEnd = e.timeStamp;
            //计算从手指接触屏幕到离开的时间,从而判断长按还是短按
            let c = eventEnd - eventStart;
            if (c >= 300) {
                e.target.dispatchEvent(longTop)
            } else {
                e.target.dispatchEvent(touch)
            }
        }
    });
})()

你可能感兴趣的:(H5,技术,移动端事件)