Touchend事件与触摸数组

时间:2017-09-17 11:37:16

标签: javascript

最近我开始玩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值,但这仍然无法解决我的问题。

1 个答案:

答案 0 :(得分:2)

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

没有接触点,没有targetTouches。

MDN TouchEvent.targetTouches

一个TouchList,列出触摸点的所有Touch对象仍然与触摸界面接触

MDN touchend

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

要解决您的问题,请在touchstart和touchmove时记录targetTouches,并在删除触摸点时使用它:

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);
});
相关问题