最近做項目經常在 chrome 的控制台看到如下提示:
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 default
簡而言之:
由於瀏覽器必須要在執行事件處理函數之後,才能知道有沒有掉用過 preventDefault() ,這就導致了瀏覽器不能及時響應滾動,略有延遲。所以為了讓頁面滾動的效果如絲般順滑,從 chrome56 開始,在 window、document 和 body 上註冊的 touchstart 和 touchmove 事件處理函數,會預設為是 passive: true。瀏覽器忽略 preventDefault() 就可以第一時間滾動了。舉例:wnidow.addEventListener('touchmove', func) 效果和下面一句一樣wnidow.addEventListener('touchmove', func, { passive: true })
這就導致了一個問題:
如果在以上這 3 個元素的 touchstart 和 touchmove 事件處理函數中調用 e.preventDefault() ,會被瀏覽器忽略掉,並不會阻止預設行為。
測試:
body { margin: 0; height: 2000px; background: linear-gradient(to bottom, red, green);}// 在 chrome56 中,照樣滾動,而且控制台會有提示,blablablawindow.addEventListener('touchmove', e => e.preventDefault())
那麼如何解決這個問題呢。不讓控制台提示,而且 preventDefault() 有效果呢。
兩個方案:
1、註冊處理函數時,用如下方式,明確聲明為不是被動的
window.addEventListener('touchmove', func, { passive: false })
2、應用 CSS 屬性
最近做項目經常在 chrome 的控制台看到如下提示:
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 default
簡而言之:
由於瀏覽器必須要在執行事件處理函數之後,才能知道有沒有掉用過 preventDefault() ,這就導致了瀏覽器不能及時響應滾動,略有延遲。所以為了讓頁面滾動的效果如絲般順滑,從 chrome56 開始,在 window、document 和 body 上註冊的 touchstart 和 touchmove 事件處理函數,會預設為是 passive: true。瀏覽器忽略 preventDefault() 就可以第一時間滾動了。舉例:wnidow.addEventListener('touchmove', func) 效果和下面一句一樣wnidow.addEventListener('touchmove', func, { passive: true })
這就導致了一個問題:
如果在以上這 3 個元素的 touchstart 和 touchmove 事件處理函數中調用 e.preventDefault() ,會被瀏覽器忽略掉,並不會阻止預設行為。
測試:
body { margin: 0; height: 2000px; background: linear-gradient(to bottom, red, green);}// 在 chrome56 中,照樣滾動,而且控制台會有提示,blablablawindow.addEventListener('touchmove', e => e.preventDefault())
那麼如何解決這個問題呢。不讓控制台提示,而且 preventDefault() 有效果呢。
兩個方案:
1、註冊處理函數時,用如下方式,明確聲明為不是被動的
window.addEventListener('touchmove', func, { passive: false })
2、應用 CSS 屬性 touch-action: none; 這樣任何觸摸事件都不會產生預設行為,但是 touch 事件照樣觸發。
touch-action 還有很多選項,詳細請參考touch-action; 這樣任何觸摸事件都不會產生預設行為,但是 touch 事件照樣觸發。
touch-action 還有很多選項,詳細請參考touch-action;
注意:touch-action: none 我實在進行下拉重新整理時候出現的該問題,所以該屬性加給下拉重新整理的容器,