创建HTML按钮并用CSS的position: fixed固定在右下角,默认隐藏;2. 通过JavaScript监听滚动事件,下滑超300px显示按钮;3. 点击按钮使用smooth行为平滑返回顶部。
实现一个“回到顶部”按钮,使用 position: fixed 可以让按钮始终固定在浏览器视窗的某个位置,比如右下角。结合简单的 HTML、CSS 和 JavaScript,就能完成这个常用功能。
#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-co
lor 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'
});
});
)代替纯文本箭头