示例
谷歌浏览器版本:Version 94.0.4606.71 (Official Build) (64-bit)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
textarea {
width: 300px;
height: 400px;
}
</style>
</head>
<body>
<textarea></textarea>
<input type="button" id="scroll-to-top" value="Scroll To Top">
<input type="button" id="scroll-to-bottom" value="Scroll To Bottom">
<script type="text/javascript">
window.onload = (event) => {
// console.log(event)
main()
}
function main() {
const textarea = document.querySelector("textarea")
const buttonScrollToTop = document.querySelector("#scroll-to-top")
const buttonScrollToBottom = document.querySelector("#scroll-to-bottom")
buttonScrollToTop.onclick = (event) => {
textarea.scroll({ top: 0, left: 0, behavior: "smooth" })
// textarea.scrollTop = 0 // 效果僵硬
}
buttonScrollToBottom.onclick = (event) => {
textarea.scroll({ top: textarea.scrollHeight, left: 0, behavior: "smooth" })
// textarea.scrollTop = textarea.scrollHeight // 效果僵硬
}
}
</script>
</body>
</html>
参考
Web technology for developers > Web APIs > Element > Element.scroll()