我正在尝试在我的react应用程序中实现点击滚动功能。我尝试使用react-scroll库window.scrollIntoView,并使用带引用的window.scrollTo。当我的应用程序溢出时,这些都不起作用,所以我不得不删除它才能让它正常工作。
.App {
height: 100vh;
overflow-y: scroll; // removing this makes click to scroll work
}我如何使用window.scrollTo
const scrollSection = useRef(null);
const goToSection = () => {
window.scrollTO({
top: scrollSection.current.offsetTop,
behavior: "smooth"
});和react-scroll:
<Link to="firstSection" spy={true} smooth={true}>
<li></li>
</Link>有没有办法让它和overflow一起工作,因为如果可能的话,我想保留overflow样式。
发布于 2021-09-16 03:28:08
在溢出元素本身上调用它,而不是在窗口上调用。HTMLElements有一个类似的函数,叫做scroll()。
document.querySelector("button").addEventListener("click", function(){
let target = document.getElementById("scroll");
document.querySelector("div").scroll({
top: target.offsetTop,
behavior: 'smooth'
});
});html, body {margin: 0}
div > p
{
height: 100px;
}
div
{
height: 100vh;
overflow: auto;
}
#scroll
{
height: 240px;
background: red;
}<div>
<button>Scroll</button>
<p>Hello</p>
<p>Hello</p>
<p>Hello</p>
<p>Hello</p>
<p>Hello</p>
<p>Hello</p>
<p>Hello</p>
<p>Hello</p>
<p>Hello</p>
<p>Hello</p>
<p>Hello</p>
<p id="scroll">Scroll to me!</p>
</div>
https://stackoverflow.com/questions/69201915
复制相似问题