event.preventDefault出错

使用mui开发移动端h5页面时, 发现Chrome的控制台不断飘红, 原来是event.preventDefault报错了.

出错代码:

1
2
// 这里的event 代表 touchstart事件
event.preventDefault()

报错如下:

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

链接中的内容如下:

AddEventListenerOptions defaults passive to false. We propose sometimes defaulting this to true in some “document level” scenarios. Specifically if an event listener is added to the document, body, or window and is a scroll blocking (touchstart, touchmove) listener it will be have its default to be true.

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.

把文章翻译成更直白点就是, event有一个cancelable属性, 只有当该属性为true时, 才能调用preventDefault方法. 由Chrome54开始, touchstart, touchmove事件的cancelable为false, 故不能调用preventDefault方法

注意到, 这是Chrome才有的特性, 比如在Firefox, touchstart事件的cancelable仍为true, 因此上面的错误在Firefox50是不会有的.

这也是浏览器的差异. 以后要阻止事件的默认行为, 应该这样写了:

1
event.cancelable && event.preventDefault()
Fork me on GitHub