簡體   English   中英

當用戶到達頁面底部香草 JS 時如何添加類

[英]How to add class when user reaches page bottom vanilla JS

我正在努力尋找對此的任何引用,但我想要實現的是在頁面滾動底部切換一個類並在向上滾動時再次將其刪除

我對 JS 不太熟悉,也不知道從哪里開始 - 我不想使用 jQuery

 var footer = document.querySelector('.site-footer'); footer.classList.toggle('show');
 section { height:150vh; } .site-footer { position: fixed; bottom:-100%; height: 200px; width: 100%; background:red; transition: bottom 0.5s ease; } .site-footer.show { bottom:0; }
 <section></section> <div class="site-footer"></div>

檢查窗口的innerHeightpageYOffset一起是否等於或大於頁面的offsetHeight

 var footer = document.querySelector('.site-footer'); window.addEventListener('scroll', () => { const atBottom = document.body.offsetHeight - (innerHeight + pageYOffset) <= 0; footer.classList.toggle('show', atBottom); }, { passive: true });
 section { height: 150vh; } .site-footer { position: fixed; bottom: -100%; height: 200px; width: 100%; background: red; transition: bottom 0.5s ease; } .site-footer.show { bottom: 0; }
 <section></section> <div class="site-footer">footer</div>

您可以為滾動事件添加一個事件偵聽器並切換“顯示”類。

 var footer = document.querySelector('.site-footer'); window.addEventListener("scroll", function(){ footer.classList.toggle('show', this.innerHeight + this.scrollY >= document.scrollingElement.scrollHeight); });
 section { height:150vh; } .site-footer { position: fixed; bottom:-100%; height: 200px; width: 100%; background:red; transition: bottom 0.5s ease; } .site-footer.show { bottom:0; }
 <section></section> <div class="site-footer"></div>

如果您不處理超級舊版瀏覽器,請使用交叉觀察器。

您不必聽滾動、准備或其他任何內容……只需聽聽邊界何時響應狀態變化並對此做出反應。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM