jquery 返回
jQuery 返回顶部功能实现
使用jQuery实现返回顶部功能可以通过监听滚动事件和动画滚动效果来完成。以下是几种常见的实现方法:
监听滚动事件并显示/隐藏返回按钮
$(window).scroll(function() {
if ($(this).scrollTop() > 100) {
$('#back-to-top').fadeIn();
} else {
$('#back-to-top').fadeOut();
}
});
平滑滚动到顶部

$('#back-to-top').click(function() {
$('html, body').animate({scrollTop: 0}, 800);
return false;
});
完整示例代码
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
#back-to-top {
position: fixed;
bottom: 20px;
right: 20px;
display: none;
background: #333;
color: #fff;
padding: 10px 15px;
border-radius: 5px;
cursor: pointer;
}
</style>
</head>
<body>
<!-- 页面内容 -->
<div style="height: 2000px;">滚动页面测试</div>
<!-- 返回顶部按钮 -->
<div id="back-to-top">返回顶部</div>
<script>
$(window).scroll(function() {
if ($(this).scrollTop() > 100) {
$('#back-to-top').fadeIn();
} else {
$('#back-to-top').fadeOut();
}
});
$('#back-to-top').click(function() {
$('html, body').animate({scrollTop: 0}, 800);
return false;
});
</script>
</body>
</html>
注意事项
滚动动画时间800毫秒可以根据需要调整,数值越大滚动越慢。

返回按钮的样式可以自定义修改,包括位置、颜色、大小等。
为确保兼容性,同时为html和body元素应用动画效果,因为不同浏览器可能使用不同的元素来管理文档滚动。
替代方案
对于现代浏览器,也可以使用纯CSS实现平滑滚动:
html {
scroll-behavior: smooth;
}
但这种方法缺乏精细控制,且不支持旧版浏览器。jQuery方案提供了更好的兼容性和控制能力。






