创建HTML按钮并用CSS的position: fixed固定在右下角,默认隐藏;2. 通过JavaScript监听滚动事件,下滑超300px显示按钮;3. 点击按钮使用smooth行为平滑返回顶部。

实现一个“回到顶部”按钮,使用 position: fixed 可以让按钮始终固定在浏览器视窗的某个位置,比如右下角。结合简单的 HTML、CSS 和 JavaScript,就能完成这个常用功能。
<button id="backToTopBtn" title="点击回到顶部">↑</button>
#backToTopBtn {
position: fixed;
bottom: 30px;
right: 30px;
width: 50px;
height: 50px;
background-color: #007bff;
color: white;
border: none;
border-radius: 50%;
font-size: 24px;
cursor: pointer;
opacity: 0;
transition: opacity 0.3s ease, background-color 0.3s ease;
z-index: 999;
}
#backToTopBtn:hover {
background-color: #0056b3;
}
#backToTopBtn.show {
opacity: 1;
}
window.addEventListener('scroll', function () {
const btn = document.getElementById('backToTopBtn');
if (window.pageYOffset > 300) {
btn.classList.add('show');
} else {
btn.classList.remove('show');
}
});
document.getElementById('backToTopBtn').addEventListener('click', function () {
window.scrollTo({
top: 0,
behavior: 'smooth'
});
});
<i class="fas fa-arrow-up"></i>)代替纯文本箭头以上就是如何通过cssfixed定位制作回到顶部按钮的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号