在JavaScript中实现“回到顶部”的功能,通常有以下几种方法:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>回到顶部示例</title>
<style>
#backToTop {
display: none;
position: fixed;
bottom: 20px;
right: 30px;
z-index: 99;
border: none;
outline: none;
background-color: #555;
color: white;
cursor: pointer;
padding: 15px;
border-radius: 10px;
}
#backToTop:hover {
background-color: #333;
}
</style>
</head>
<body>
<div style="height: 2000px;">
<!-- 页面内容 -->
</div>
<button onclick="topFunction()" id="backToTop" title="回到顶部">Top</button>
<script>
// 获取按钮
let mybutton = document.getElementById("backToTop");
// 当用户向下滚动 20px 显示按钮
window.onscroll = function() { scrollFunction(); };
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
mybutton.style.display = "block";
} else {
mybutton.style.display = "none";
}
}
// 当用户点击按钮,滚动到顶部
function topFunction() {
document.body.scrollTop = 0; // For Safari
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
}
</script>
</body>
</html>
function topFunction() {
window.scrollTo({ top: 0, behavior: 'smooth' });
}
window.onscroll
事件正确绑定。window.scrollTo
方法的behavior: 'smooth'
选项来实现平滑滚动。behavior: 'smooth'
的浏览器,可以使用polyfill或回退到基本的滚动方法。通过以上方法,你可以轻松实现一个“回到顶部”的功能,并根据需要进行定制和优化。
领取专属 10元无门槛券
手把手带您无忧上云