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;
});
CSS 固定定位样式
#back-to-top {
position: fixed;
bottom: 20px;
right: 20px;
display: none;
cursor: pointer;
z-index: 999;
}
完整示例代码
<!DOCTYPE html>
<html>
<head>
<style>
#back-to-top {
position: fixed;
bottom: 20px;
right: 20px;
display: none;
background: #333;
color: #fff;
padding: 10px 15px;
border-radius: 5px;
cursor: pointer;
z-index: 999;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</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>
注意事项
- 确保 jQuery 库已正确加载
- 调整
scrollTop() > 100中的阈值以控制何时显示置顶按钮 - 动画持续时间(800ms)可根据需要调整
- 对于固定导航栏,只需使用 CSS 的
position: fixed并设置合适的top值







