做下拉重新整理時候控制台一直列印:Unable to preventDefault inside passive event listener

來源:互聯網
上載者:User

最近做項目經常在 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   我實在進行下拉重新整理時候出現的該問題,所以該屬性加給下拉重新整理的容器,

    



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.