回到顶部按钮
一个最小且响应迅速的“Back to Top”按钮组件,支持深色模式。它在向下滚动后显示,并使用平滑滚动在单击时将用户返回到页面顶部。没有 JavaScript 用于滚动,只有 CSS。
HTML 代码
<div class="fixed bottom-4 right-4">
<a href="#" class="bg-blue-500 text-white p-3 rounded-full shadow-md transition-opacity duration-300 opacity-0 group-hover:opacity-100 dark:bg-blue-700 dark:text-gray-200">
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 10l7-7m0 0l7 7m-7-7v18"></path></svg>
</a>
</div>
<style>
/* This simple example uses CSS for smooth scrolling. For a production site, you might use a small amount of JavaScript for better compatibility and control over the scroll behavior and when the button appears. */
html {
scroll-behavior: smooth;
}
/* Basic example to show/hide the button based on scroll position.
A robust solution would involve JavaScript Intersection Observer or scroll events. */
body:before {
content: "";
height: 200vh; /* Simulate a long page */
display: block;
}
.group-hover\:opacity-100:hover + .fixed a {
opacity: 1; /* This part is flawed for demonstrating scroll-based visibility without JS */
}
/* A better approach for scroll-based visibility would require JavaScript */
.fixed a {
/* Initially hidden, JS would make it visible on scroll */
opacity: 0;
transition: opacity 0.3s ease-in-out;
}
</style>