<button id="backToTop">返回顶部</button>
<style>
#backToTop {
display: none; /* 初始状态隐藏按钮 */
position: fixed;
bottom: 20px;
right: 20px;
padding: 10px 15px;
background-color: #007BFF;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
transition: opacity 0.3s; /* 添加淡入淡出效果 */
opacity: 0;
}
#backToTop.show {
display: block;
opacity: 1;
}
</style>
<script>
const backToTopButton = document.getElementById('backToTop');
// 监听滚动事件
window.addEventListener('scroll', () => {
if (window.pageYOffset > 300) { // 当页面滚动超过300像素时显示按钮
backToTopButton.classList.add('show');
} else {
backToTopButton.classList.remove('show');
}
});
// 点击按钮时滚动到顶部
backToTopButton.addEventListener('click', () => {
window.scrollTo({top: 0, behavior: 'smooth'});
});
</script>