Javascript ontouchstart/move/end - 得到奇怪的结果

Ant*_*erg 4 javascript touch coordinates swipe

我正在为平板电脑/智能手机构建这个具有滑动功能的图片库。我在 iPad 上得到了非常奇怪的结果,所以我决定一直跟踪到开始,并在不同事件发生时打印出来。

以下代码应该在我用手指完成滑动后发出类似以下内容的警报:“start.move.move.move.end”(“移动”的次数由滑动操作的时间长短决定)。

        itemWrap[0].ontouchstart = function(e) {
            _self.msg.push("start");

        }

        itemWrap[0].ontouchmove = function(e) {
            _self.msg.push("move");
        }

        itemWrap[0].ontouchend = function(e) {
            _self.msg.push("end");

            // join messages and alert to browser
            msg = _self.msg.join(".") || "empty";
            alert(msg);
        }
Run Code Online (Sandbox Code Playgroud)

然而,我收到了非常奇怪的警报,并且它们在 Android/iOS 设备上差异很大。在 Android 上,大多数时候结果看起来都符合预期:

“开始.移动.移动.移动.移动.结束”

“start.end”(轻拂屏幕时)

“start.move.start.end”(每次其他触摸操作都会发生这种情况)

但在 iPad 上我得到了一些非常奇怪的结果。在第一次触摸操作中,我得到了我所期望的结果,但在第二次触摸时,包含结果的警报(“start.move.move.move.end”)在触摸屏幕时立即触发,并且它始终包含之前的结果。当我第三次触摸屏幕时,它再次返回到常规操作,并且对于所有其他触摸操作也是如此。

我四处寻找有类似问题的人,但我似乎得到的最接近的是用户在多点触控操作方面遇到问题(我对此不感兴趣)。关于为什么会发生这种情况有什么建议吗?

小智 5

您必须记住,触摸是多点触摸,它不像鼠标事件那样总是一次。每次收到触摸事件(touchstart、touchstart、touchend)时,您还会获得标识符

itemWrap[0].ontouchstart = function(e) {
    // e.touches.length - number of touches
    // e.touches[e.touches.length - 1].identifier - last touch is the last one on the list
    // e.touches[e.touches.length - 1].pageX and .pageY - place of the touch
    _self.msg.push("start");
}
Run Code Online (Sandbox Code Playgroud)

因此,当您执行 touchmove 和 touchend 时,您必须检查该标识符以查看哪个触摸被移动或结束。您可以通过将该数据保存在 touchstart 中来做到这一点:

var t = {pageX:event.touches[index].pageX, pageY:event.touches[index].pageY, identifier:event.touches[index].identifier};
touches.push(t);
Run Code Online (Sandbox Code Playgroud)

然后使用以下命令在 touchend 中找到正确的触摸

event.changedTouches[0].identifier
Run Code Online (Sandbox Code Playgroud)

在这里,您不需要浏览该列表,因为它总是只有一个,但您必须将该标识符与列表中保存的标识符进行比较。

希望这会有所帮助。