chrome passive event listener 报错

针对Chrome56更新后,默认将touchstart和touchmove事件设为passive:true的问题,本文介绍了三种解决方案,包括设置passive:false、使用CSS touch-action属性及自定义事件监听器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

错误信息:Unable to preventDefault inside passive event listener due to target being treated as passive.

是时候 google 了。

在 chrome 56 版本的更新日志中又这样一段话。

AddEventListenerOptions defaults passive to false. With this change touchstart and touchmove listeners added to the document will default to passive:true (so that calls to preventDefault will be ignored)..
If the value is explicitly provided in the AddEventListenerOptions it will continue having the value specified by the page.
This is behind a flag starting in Chrome 54, and enabled by default in Chrome 56. See
https://developers.google.com/web/updates/2017/01/scrolling-intervention

又看到 google 曾发过这样几篇博客。(需要翻墙)
passive-event-listeners
scrolling-intervention

经过一番折腾,大概知道了为什么。(看博客下的评论,程序员们对这一改动一片“叫好“,呵呵~)

google 这一改动是为了移动端滚动更加流畅,在 chrome 56 版本之后,对 touchstart 和 touchmove 事件处理函数,会默认设为 passive: true。因此默认也会忽略 preventDefault() 的调用。

也就是这样:

window.addEventListener('touchmove', func) 
window.addEventListener('touchmove', func, { passive: true }) // 默认为 true,等同上句

那么知道导致问题的原因,怎么解决呢?

1、方案一:

window.addEventListener('touchmove', func, { passive: false }) // 取消被动模式

2、方案二:

body {
    touch-action: none
}

通过这个可以防止触发默认事件,同时touch相关事件还能保持有效。

3、方案三:

document.body.addEventListener('touchmove', function(e) {
    // 判断默认事件是否可以禁止
    if (e.canelable) {
        e.preventDefault();
    }
})

第三种方案,pc端和移动端表现不一致,刚好可以避免pc端报这个错误。不过测试过程中,还有其他不确定问题,不建议用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值