【问题标题】:Should I use touch-action: none instead of preventDefault() to stop scrolling on touch device?我应该使用 touch-action: none 代替 preventDefault() 来停止在触摸设备上滚动吗?
【发布时间】:2017-02-27 13:33:33
【问题描述】:

我一直在尝试停止在触摸设备中滚动,为此我使用了 touchmove 事件:

$('body').on('touchmove.sidebar', function(e){                        
  e.preventDefault();
});

在 Chrome 控制台中,我看到警告:

由于目标,无法在被动事件侦听器中阻止默认值 被视为被动。看 https://www.chromestatus.com/features/5093566007214080

github 上,建议使用touch-action: none 而不是preventDefault()。所以我的问题是:

我应该同时使用preventDefault()touch-action: none 还是只使用后者?后者是否适用于 firefox 和其他触摸浏览器?

【问题讨论】:

    标签: javascript css google-chrome scroll


    【解决方案1】:

    您在 Chrome 中看到警告的原因是,默认情况下,从 Chrome 版本 54 开始,为了提高滚动性能,它假定不会为文档级别调用 preventDefault()

    我没怎么用过jQuery,用简单的js:

    body.addEventListener("touchmove", function(e){}, passive:false);
    

    Check this answer out

    注意 1:确保您提供了另一种滚动方式 您的页面是否需要滚动。

    注意 2:尝试将事件处理程序添加到 HTML 页面中的特定元素 如果可能,而不是 HTML 正文。

    现在回答你的问题:

    你不需要两者,任何一个都足够了。根据您的要求决定。

    1. 检查caniuse,如果您对touch-action 所提供的浏览器支持感到满意,那就去吧。

    2. 如果您对它提供的支持不满意,请使用preventDefault() 方法。

    注意:preventDefault() 方法只有在 指定的事件正在发生,并通过指定样式 touch-action:none,相应元素的 touchEvents 不会 只要应用了这种样式,就会被触发。

    请查看此链接以了解更多信息: https://www.html5rocks.com/en/mobile/touchandmouse/

    【讨论】:

    • 你有一个错误,而不是passive:false,你应该有{passive:false}。此代码帮助我防止桌面 chrome 上的默认触摸事件:document.addEventListener("touchstart", function(e){e.preventDefault();},{passive: false});
    猜你喜欢
    • 1970-01-01
    • 2012-12-01
    • 2014-09-20
    • 2014-01-04
    • 1970-01-01
    • 1970-01-01
    • 2015-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多