jQuery 返回顶部和底部特效是一种常见的网页交互功能,允许用户通过点击按钮快速滚动到页面的顶部或底部。这种特效通常用于长页面,以提高用户体验。
以下是一个简单的 jQuery 返回顶部和底部特效的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery 返回顶部底部特效</title>
<style>
#back-to-top, #back-to-bottom {
display: none;
position: fixed;
padding: 10px;
background-color: #007bff;
color: white;
cursor: pointer;
border-radius: 5px;
}
#back-to-top {
bottom: 20px;
right: 20px;
}
#back-to-bottom {
top: 20px;
right: 20px;
}
</style>
</head>
<body>
<div style="height: 2000px;">
<!-- 页面内容 -->
</div>
<button id="back-to-top">返回顶部</button>
<button id="back-to-bottom">返回底部</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;
});
// 显示/隐藏返回底部按钮
$(window).scroll(function() {
if ($(this).scrollTop() < $(document).height() - $(window).height() - 100) {
$('#back-to-bottom').fadeIn();
} else {
$('#back-to-bottom').fadeOut();
}
});
// 返回底部按钮点击事件
$('#back-to-bottom').click(function() {
$('html, body').animate({ scrollTop: $(document).height() }, 800);
return false;
});
});
</script>
</body>
</html>
animate
方法中的动画时长和缓动函数。通过以上方法,你可以实现一个简单且高效的返回顶部和底部特效,提升用户体验。
领取专属 10元无门槛券
手把手带您无忧上云