[英]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.