回到顶部(Scroll to Top)功能允许用户通过点击一个按钮快速返回到页面的顶部。这个功能在长页面中尤其有用,可以提升用户体验。
使用原生JavaScript实现回到顶部功能主要涉及以下几个步骤:
window.scrollTo
方法将页面滚动到顶部。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Scroll to Top Example</title>
<style>
#scrollToTopBtn {
display: none;
position: fixed;
bottom: 20px;
right: 30px;
z-index: 99;
font-size: 18px;
border: none;
outline: none;
background-color: #555;
color: white;
cursor: pointer;
padding: 15px;
border-radius: 4px;
}
#scrollToTopBtn:hover {
background-color: #777;
}
</style>
</head>
<body>
<button id="scrollToTopBtn" title="Go to top">Top</button>
<div style="height:2000px;">
<!-- Your content here -->
</div>
<script>
// Get the button
let mybutton = document.getElementById("scrollToTopBtn");
// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
mybutton.style.display = "block";
} else {
mybutton.style.display = "none";
}
}
// When the user clicks on the button, scroll to the top of the document
mybutton.onclick = function() {
window.scrollTo({top: 0, behavior: 'smooth'});
};
</script>
</body>
</html>
问题1:滚动效果不平滑
behavior: 'smooth'
属性。window.scrollTo
方法中添加behavior: 'smooth'
属性。问题2:按钮显示/隐藏逻辑错误
通过以上步骤和示例代码,您可以轻松实现一个原生JavaScript的回到顶部功能,并确保其在各种场景下都能良好运行。
领取专属 10元无门槛券
手把手带您无忧上云