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

 mobiledu2502856247 发布于 2023-02-12 15:48

当使用带有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;
}
}

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

2 个回答
  • 最后我找到了解决方案(纯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);
    
    }
    

    希望这有帮助.

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

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

      touchstart,将坐标存储在变量中,并设置iteration为0.

      对于每个touchmove事件,设置iterationiteration+1.

      iteration等于4(只是我发现在我的设置中可靠的"幻数")时,计算x轴和y轴的总触摸偏移增量.编辑:在移动设备上,你只会收到一个没有event.preventDefault()的touchmove

      如果x轴偏移> y轴偏移*3,则触发event.preventDefault().(这可以确保手势非常水平)

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

    2023-02-12 15:51 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有