關於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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM