【问题标题】:Touchend event not working correctly with touches arrayTouchend 事件无法与 touches 数组一起正常工作
【发布时间】:2018-02-26 01:34:40
【问题描述】:

最近我开始在 javascript 中使用触摸事件,但我遇到了一个关于 touchend 事件的奇怪问题(可能是一些显而易见的事情,我只是太笨了,无法理解它)。所以基本上,这是我的代码:

function send(e) {
    e.preventDefault();
    document.body.innerHTML = e.type + "<br>" + e.targetTouches[0].pageY;
}

['touchstart', 'touchmove', 'touchend'].forEach(function(e) {
    window.addEventListener(e, send, false);
});

现在 e.targetTouches[0].pageY 工作正常,但 e.type 将只假设 touchstart 或 touchmove 值,而不是由于某种原因的 touchend .我注意到只有当我尝试在同一行中调用 e.type 属性或从 event.targetTouches(或 event.touches)数组中读取任何属性后才会发生这种情况。这些属性不是只读的吗?为什么它会破坏我的代码?

哦,玩了几个小时后,我注意到 event.type 只有在将一根手指放在屏幕上然后用另一根手指点击它时才会采用 touchend 值,但这仍然不能解决我的问题。

【问题讨论】:

    标签: javascript


    【解决方案1】:

    这是因为触摸点被移除时触发了 touchend 事件。

    没有接触点,没有目标触摸。

    MDNTouchEvent.targetTouches

    一个 TouchList 列出了所有 触摸点仍与触摸表面接触

    的触摸对象

    MDNtouchend

    touchend 事件在 触摸点从触摸表面移除时触发

    为了解决你的问题,在touchstart和touchmove时记录targetTouches,并在touch point被移除时使用:

    var TargetTouches;
    
    function send(e) {
    
        e.preventDefault();
    
        var type = e.type;
        var pageY;
    
        if (type !== 'touchend') {
          pageY = e.targetTouches[0].pageY;
          TargetTouches = e.targetTouches[0];
        } else {
          pageY = TargetTouches.pageY;
        }
    
        document.body.innerHTML = type + "<br>" + pageY;
    }
    
    ['touchstart', 'touchmove', 'touchend'].forEach(function(e) {
        window.addEventListener(e, send, false);
    });
    

    【讨论】:

    • 这如何解决我的问题? Touchend 事件工作正常,假设发送函数的第一行类似于“alert(e.type);”然后当我点击屏幕时,它会同时提醒“touchstart”和“touchend”,但是当我尝试在 event.targetTouches[0].someProperty(或 event.touches[0].someProperty)之后提醒它时,touchend 事件会神奇地消失,就像它从未触发过,但 touchstart 和 touchmove 工作正常......
    • 去掉代码'e.targetTouches[0].pageY',就可以看到touchend事件被触发了,并没有消失
    • 正如我在问题中所说,我已经知道“e.targetTouches[0].pageY”会导致 touchend 出现问题,而不是避免问题,我想修复它或了解它的原因不会工作,并找到一些替代方法来做到这一点。删除它什么也没给我。
    • 谢谢!现在举个例子,这对我来说很有意义,我将触摸事件与 mouseup 仍然记录坐标的鼠标事件进行比较是我的错。
    猜你喜欢
    • 2015-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-07
    • 1970-01-01
    • 2021-02-12
    • 2020-10-10
    相关资源
    最近更新 更多