[英]React - How to get the scroll position of a div in JS
我有一個側面導航欄,里面有一個標題和一些其他信息,標題名稱是粘性的,側面板的高度為 100vh。 我希望我的標題 div( sticky-title
)只有在用戶向下滾動時(上下文大於 100vh)才有box-shadow
。 換句話說, box-shadow 屬性最初不應該在那里,但是當用戶向下滾動頁面時它應該出現。 我嘗試觸發滾動 EventListener 但它正在獲取主窗口的滾動位置,盡管我希望考慮側邊欄 div 的滾動位置。
下面是相同的代碼沙盒游樂場鏈接。
看看這個變化是否可以幫助你在App.js
:
useEffect(() => {
// Select the title wrapper
const title = document.querySelector('.sticky-title');
const titleTop = title.offsetTop; // find the top position of title block
// relative to the window top
window.addEventListener("scroll", () => {
console.log("hi", titleTop);
setScroll(this.scrollY >= titleTop); // when window.scrollY is greater than top
// the top of the title block the scroll
// state is set to True
});
}, []);
也在App.js
的 JSX 部分:
<div className="panel" style={{ height: 2000 }}>{/*2000px to scroll the page easier*/}
...
</div>
和style.css
:
.panel {
width: 200px;
height: 100vh;
border: 2px solid black;
white-space: pre-line;
/* overflow: auto; */ <---- delete this because it prevents position: sticky to work
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.