源码介绍
当你滚动到页面底部时,右下角会出现一个箭头按钮,点击它可以快速返回到页面顶部。
这个功能对于长页面非常有用,可以提高用户体验,减少用户查找导航元素的时间。 返回顶部按钮通常设计为固定在页面上,不随内容滚动,并且在不需要时保持隐藏状态。
复制下面代码,加入到你的网站首页即可实现
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>返回顶部示例</title>
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="external nofollow" rel="stylesheet">
<script>
tailwind.config = {
theme: {
extend: {
colors: {
primary: '#3B82F6',
},
}
}
}
</script>
<style type="text/tailwindcss">
@layer utilities {
.back-to-top {
@apply fixed bottom-6 right-6 bg-primary text-white w-12 h-12 rounded-full flex items-center justify-center shadow-lg opacity-0 transition-all duration-300 hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-primary/50 z-50;
}
.back-to-top.active {
@apply opacity-100 pointer-events-auto;
}
}
</style>
</head>
<body class="font-sans bg-gray-50 text-gray-800 min-h-screen">
<!-- 返回顶部按钮 -->
<button id="backToTop" class="back-to-top" aria-label="返回顶部">
<i class="fa fa-arrow-up text-xl"></i>
</button>
<!-- 增加足够的内容让页面可以滚动 -->
<div class="h-[200vh]"></div>
<script>
// 返回顶部按钮功能
document.addEventListener('DOMContentLoaded', function() {
const backToTopButton = document.getElementById('backToTop');
// 监听滚动事件
window.addEventListener('scroll', function() {
// 当页面滚动超过300px时显示按钮
if (window.scrollY > 300) {
backToTopButton.classList.add('active');
} else {
backToTopButton.classList.remove('active');
}
});
// 点击按钮时平滑滚动到顶部
backToTopButton.addEventListener('click', function() {
window.scrollTo({
top: 0,
behavior: 'smooth'
});
});
});
</script>
</body>
</html>