"返回顶部"(Back to Top)是一个常见的网页功能,允许用户点击一个按钮快速滚动到页面顶部。这个功能通常用于长页面,以提高用户体验。
以下是一个使用jQuery实现返回顶部功能的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>返回顶部示例</title>
<style>
#back-to-top {
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;
}
#back-to-top:hover {
background-color: #777;
}
</style>
</head>
<body>
<div style="height: 2000px;">
<!-- 页面内容 -->
</div>
<button id="back-to-top" title="返回顶部">Top</button>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$(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>
back-to-top
。$(window).scroll()
监听窗口滚动事件。$('html, body').animate()
方法平滑滚动到页面顶部。animate()
方法是否正确调用。通过以上步骤,你可以实现一个简单且有效的返回顶部功能。
领取专属 10元无门槛券
手把手带您无忧上云