关于Google浏览器Unable to preventDefault inside passive event listener due to target being treated as passive.的解决方案

最近写react项目的时候,引用了antd-mobile,在使用滚动组件的时候,发现谷歌浏览器会报以下警告

最初我以为是antd-mobile的问题导致的,然后我就无查看了之前的vue的项目,发现了类似的问题,这是为什么呢?

更具这篇文章https://developers.google.cn/web/updates/2017/01/scrolling-intervention找到了答案

1 由于浏览器必须要在执行事件处理函数之后,才能知道有没有掉用过 preventDefault() ,这就导致了浏览器不能及时响应滚动,略有延迟。
2 
3 所以为了让页面滚动的效果如丝般顺滑,从 chrome56 开始,在 window、document 和 body 上注册的 touchstart 和 touchmove 事件处理函数,会默认为是 passive: true。浏览器忽略 preventDefault() 就可以第一时间滚动了。
4 
5 举例:
6 wnidow.addEventListener('touchmove', func) 效果和下面一句一样
7 wnidow.addEventListener('touchmove', func, { passive: true })
这就导致了一个问题:

如果在以上这 3 个元素的 touchstart 和 touchmove 事件处理函数中调用 e.preventDefault() ,会被浏览器忽略掉,并不会阻止默认行为。
1 那么如何解决这个问题呢?不让控制台提示,而且 preventDefault() 有效果呢?
2 两个方案:
3 1、注册处理函数时,用如下方式,明确声明为不是被动的
4 window.addEventListener('touchmove', func, { passive: false })
5 
6 2、应用 CSS 属性 touch-action: none; 这样任何触摸事件都不会产生默认行为,但是 touch 事件照样触发。

这里是touch-action 的详细解释https://w3c.github.io/pointerevents/#the-touch-action-css-property

原文地址:https://www.cnblogs.com/songdongdong/p/9115668.html