Javascript:除了使用event.preventDefault()之外,让Chrome for Android触发touchmove和touchend事件监听器的任何变通办法?

Kyl*_*ems 10 javascript events android google-chrome

当使用带有touchmove和touchend事件的事件监听器时,除非我首先使用event.preventDefault();否则我无法让Chrome for Android承认这些事件.在代码的早期.如果我不想阻止默认滚动功能,我是否可以使用其他解决方法让Chrome for Android承认这些事件?

示例代码:

$(document).ready(function () {
// Bind touch event listeners.
var elem = $('html').get(0);
elem.addEventListener('touchstart', function (e) { console.info('"touchstart" detected. Coordinates - ' + getCoord(e)); });
elem.addEventListener('touchmove', function (e) { console.info('"touchmove" detected. Coordinates - ' + getCoord(e)); });
elem.addEventListener('touchend', function (e) { console.info('"touchend" detected. Coordinates - ' + getCoord(e)); });

function getCoord(e) {
var touch = false;
if (e.touches.length > 0) {
touch = e.touches[0];
} else {
touch = e.changedTouches[0];
}
if (touch) {
return 'x: ' + touch.pageX + ', y: ' + touch.pageY;
}
}
Run Code Online (Sandbox Code Playgroud)

示例小提琴:http://jsfiddle.net/jQ2VS/1/

Hen*_*han 12

如果Google Chrome 认为用户正在平移/滚动并且您没有通话touchcancel,touchstart那么它将在大约200毫秒后触发一个事件event.preventDefault().

假设您要拦截水平触摸事件并让垂直触摸事件导致平移/滚动,则解决方法是:

  1. touchstart,将坐标存储在变量中,并设置iteration为0.
  2. 对于每个touchmove事件,设置iterationiteration+1.
  3. iteration等于4(只是我发现在我的设置中可靠的"幻数")时,计算x轴和y轴的总触摸偏移增量.编辑:在移动设备上,你只会收到一个没有event.preventDefault()的touchmove
  4. 如果x轴偏移> y轴偏移*3,则触发event.preventDefault().(这可以确保手势非常水平)

这方面的缺点是用户只能向左/向右滑动或向上/向下滚动.

  • 我发现桌面上的神奇值为4,而移动装置仅为1.如果您仅定位到移动设备,那么如果触摸增量处于非常水平的位置,您可能会在第一次触摸时调用event.preventDefault().这也是Android的GMail应用程序抽屉所观察到的行为:一旦开始滑动,就无法滚动,当您滚动时,您无法滑动打开/关闭抽屉. (2认同)

Gio*_*rio 7

最后我找到了解决方案(纯js),即使你可能想用它来滑动:

var swipe = function() {

    var touchX, touchY, movX, movY, go;

    function prevent(e){
        e.preventDefault();
    }

    function start(e) {
        go = false;
        document.addEventListener("touchmove", prevent, false);
        touchX = e.touches[0].pageX;
        touchY = e.touches[0].pageY;
    }

    function move(e) {
        movX = e.touches[0].pageX - touchX;
        movY = e.touches[0].pageY - touchY;
        if(!go) {
            (Math.abs(movY) < Math.abs(movX)) ? go = true : stop(e);
        } else {
            /* *************** */
            // cast your spell
            /* *************** */
        }
    }

    function stop(e) {
        document.removeEventListener("touchmove", prevent, false);
    }

    document.addEventListener("touchstart", start, true);
    document.addEventListener("touchmove", move, true);
    document.addEventListener("touchend", stop, true);
    document.addEventListener("touchleave", stop, true);
    document.addEventListener("touchcancel", stop, true);

}
Run Code Online (Sandbox Code Playgroud)

希望这有帮助.