Javascript - touchstart 和 touchend 位置

Javascript - touchstart and touchend locations

如果元素“#menu”被触摸,我想获取 touchstart 和 touchend 位置。

我写了这段代码,但事件似乎根本没有触发:

        var lastLoc = 0;

        $(document).on('touchstart', '#menu', function(e) {
            lastLoc = e.originalEvent.touches[0].pageX;
        });

        $(document).on('touchend', '#menu', function(e) {
            var newLoc = e.originalEvent.touches[0].pageX;
            alert("lastLoc = "+lastLoc+", newLoc = "+newLoc);
        });

据我所知这应该有效。

提前致谢。

从逻辑上讲,touchend 事件应该有零个 touch 分,只有 changedTouches.

Here's a demo.

function startHandler (e) {
    window.console.log('Start:', e.originalEvent.touches[0].pageX);
}

function endHandler (e) {
    window.console.log('End:', e.originalEvent.changedTouches[0].pageX);
}



$(document).on('touchstart', '#menu', startHandler);
$(document).on('touchend', '#menu', endHandler);

另请参阅:Simulating touchstart and touchend events? 如果您在测试触摸事件时遇到问题。

您需要在智能手机或平板电脑等可触摸表面上测试触摸事件。 在GoogleChrome中有一种方法可以模拟这个功能。

抱歉给您带来麻烦,我最后使用的是 jquery 手机 "swipeleft" 无论如何谢谢:)