scrollTo 或 react-scroll 不适用于溢出
scrollTo or react-scroll doesn't work with overflow
我正在尝试在我的 React 应用程序中实现点击滚动功能。我尝试使用 react-scroll
库,window.scrollIntoView
,并使用 window.scrollTo
和 ref。这些不适用于我的应用程序溢出,因此我不得不将其删除以使其正常工作。
.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"
});
和反应滚动:
<Link to="firstSection" spy={true} smooth={true}>
<li></li>
</Link>
有没有办法让它与溢出一起工作,因为我想尽可能保留溢出样式。
在溢出元素本身上调用它,而不是在 window 上调用它。 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>
我正在尝试在我的 React 应用程序中实现点击滚动功能。我尝试使用 react-scroll
库,window.scrollIntoView
,并使用 window.scrollTo
和 ref。这些不适用于我的应用程序溢出,因此我不得不将其删除以使其正常工作。
.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"
});
和反应滚动:
<Link to="firstSection" spy={true} smooth={true}>
<li></li>
</Link>
有没有办法让它与溢出一起工作,因为我想尽可能保留溢出样式。
在溢出元素本身上调用它,而不是在 window 上调用它。 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>