javascript - scrollToTop 在反应中不起作用(codesandbox)
问题描述
作为反应,我试图让 scrollToTop 工作。
不知何故,它不起作用。
https://codesandbox.io/s/quiet-shape-5iov0?file=/src/App.js这是codesandbox。向下滚动,应该有一个按钮,称为click
向上滚动,但它不起作用。
解决方案
如果您只需要滚动顶部,请尝试此操作。
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
推荐阅读
- python - 在 PDF 中搜索信息
- webrtc - WebRTC 媒体聊天中网络更改后的无效对等连接
- python-3.x - 如何使用 TLS 连接与服务器通信?
- kotlin - 如何在 Kotlin 中打乱可变列表的元素?
- c++ - pybind11(嵌入)导入到根命名空间
- javascript - .eslintrc 中的“插件”属性有什么作用?
- firebase - 如果文档 ID 包含字符串,则 Firebase Firestore 安全规则允许
- python - 在 Python 中使用“adb shell”
- python - 通过 python 运行 vba 宏,但你可以在 python 中添加进度条来测量 vba 进程吗?
- python - 如何将数据从表单保存到 django 模型?