Unable to preventDefault inside passive event listener

 

 

最近作项目常常在 chrome 的控制台看到以下提示:css

Unable to preventDefault inside passive event listener due to target being treated as passive. See https://www.chromestatus.com/features/5093566007214080

因而 Google 了一番,找到这篇文章,有了详细解释。Making touch scrolling fast by defaultgit

简而言之:github

因为浏览器必需要在执行事件处理函数以后,才能知道有没有掉用过 preventDefault() ,这就致使了浏览器不能及时响应滚动,略有延迟。

因此为了让页面滚动的效果如丝般顺滑,从 chrome56 开始,在 window、document 和 body 上注册的 touchstart 和 touchmove 事件处理函数,会默认为是 passive: true。浏览器忽略 preventDefault() 就能够第一时间滚动了。 举例: wnidow.addEventListener('touchmove', func) 效果和下面一句同样 wnidow.addEventListener('touchmove', func, { passive: true })

这就致使了一个问题:web

若是在以上这 3 个元素的 touchstart 和 touchmove 事件处理函数中调用 e.preventDefault() ,会被浏览器忽略掉,并不会阻止默认行为。

测试:chrome

body {
  margin: 0; height: 2000px; background: linear-gradient(to bottom, red, green); } // 在 chrome56 中,照样滚动,并且控制台会有提示,blablabla window.addEventListener('touchmove', e => e.preventDefault())

那么如何解决这个问题呢?不让控制台提示,并且 preventDefault() 有效果呢?
两个方案:
一、注册处理函数时,用以下方式,明确声明为不是被动的
window.addEventListener('touchmove', func, { passive: false })typescript

二、应用 CSS 属性 touch-action: none; 这样任何触摸事件都不会产生默认行为,可是 touch 事件照样触发。
touch-action 还有不少选项,详细请参考touch-actionsegmentfault

[注]将来可能全部的元素的 touchstart touchmove 事件处理函数都会默认为 passive: true浏览器

相关文章
相关标签/搜索