關於Google瀏覽器Unable to preventDefault inside passive event listener due to target being treated as ...

最近寫react項目的時候,引用了antd-mobile,在使用滾動組件的時候,發現谷歌瀏覽器會報如下警告css

最初我覺得是antd-mobile的問題致使的,而後我就無查看了以前的vue的項目,發現了相似的問題,這是爲何呢?vue

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

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 二、應用 CSS 屬性 touch-action: none; 這樣任何觸摸事件都不會產生默認行爲,可是 touch 事件照樣觸發。

這裏是touch-action 的詳細解釋https://w3c.github.io/pointerevents/#the-touch-action-css-propertygit