作为反应,我试图让 scrollToTop 工作。
不知何故,它不起作用。
full working example 这是代码和框。向下滚动,应该有一个名为 click
的按钮向上滚动,但它不起作用。
答案 0 :(得分:3)
如果您只需要滚动顶部,请尝试此操作。
window.scrollTo({
top: 0,
left: 0,
behavior: "smooth"
});
功能
const nice = () => {
window.scrollTo({
top: 0,
left: 0,
behavior: "smooth"
});
};
使用 scrollIntoView()
const nice = () => {
document.querySelector("body").scrollIntoView({
behavior: "smooth"
});
};
为了更好地理解,请查看 window.scrollTo
答案 1 :(得分:0)
scrollTo 是一个窗口函数,所以只需将其附加到那里:)
window.scrollTo({
top: 0,
left: 0,
behavior: "smooth"
});
答案 2 :(得分:0)
您可以像这样使用窗口对象滚动到顶部:
window.scrollTo(0,0)
答案 3 :(得分:0)
如果您不想使用 window
对象
const nice = () => {
const root = document.querySelector("body");
console.log(root, " root");
root.scrollIntoView({
behavior: "smooth"
});
};