Unable to preventDefault inside passive event listener

转自:https://segmentfault.com/a/1190000008512184css

 

测试:git

 
body {
  margin: 0;
  height: 2000px;
  background: linear-gradient(to bottom, red, green);
}

// 在 chrome56 中,照样滚动,并且控制台会有提示,blablabla
window.addEventListener('touchmove', e => e.preventDefault())

  

那么如何解决这个问题呢?不让控制台提示,并且 preventDefault() 有效果呢?
两个方案:
一、注册处理函数时,用以下方式,明确声明为不是被动的
var func = function(e){ github

e.preventDefault();//firefox等
e.returnValue = false;chrome

}
window.addEventListener('touchmove', func, { passive: false })segmentfault

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

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

相关文章
相关标签/搜索