js触摸事件

检测是否存在e.touches.length,如果存在则支持触摸事件

记录第一次手指按下的位置 同时监听手指移动和手指松开事件。

function touchStart(e) {
    if(!e.touches.length) return;
    var touch = e.touches[0]
    startX = touch.pageX;
    startY = touch.pageY;
    elem.addEventListener('touchmove',touchMove,false);
    elem.addEventListener('touchend',touchEnd,false);
}

手指移动

function touchMove(e) {
    e.preventDefault();
    if(!e.touches.length) return;
    var touch = e.touches[0],
        pgx = touch.pageX,
        pgy = touch.pageY;
    x = pgx - startX,
        y = pgy - startY;
    //逻辑处理
}

手指松开

function touchEnd() {
    //逻辑处理
}

开始监听手指按下事件

if("ontouchstart" in document) {
    elem.addEventListener('touchstart',touchStart,false);
}

上述操作,可以基本完成简单的触摸事件监听!

如果您觉得本文对您有用,欢迎捐赠或留言~
微信支付
支付宝

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注