add backToTop button

This commit is contained in:
Steven Lynn
2024-08-06 17:46:59 +08:00
parent a1b7f80017
commit 348192f1b9
3 changed files with 69 additions and 2 deletions

View File

@@ -123,3 +123,33 @@
display: block;
}
}
#back-to-top {
position: fixed;
bottom: 20px;
right: 20px;
background-color: #dfd3c3;
color: #333;
width: 50px;
height: 50px;
border-radius: 50%;
border: none;
cursor: pointer;
display: none; /* 初始状态隐藏 */
align-items: center;
justify-content: center;
font-size: 24px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
z-index: 1000;
transition: all 0.3s ease; /* 添加过渡效果 */
}
#back-to-top:hover {
background-color: #d0c3b4; /* 稍微深一点的颜色作为悬停效果 */
transform: translateY(-3px); /* 悬停时稍微上移 */
}
#back-to-top:active {
transform: translateY(1px); /* 点击时下移,创造按压效果 */
box-shadow: 0 1px 5px rgba(0, 0, 0, 0.2); /* 减小阴影 */
}

View File

@@ -73,7 +73,9 @@ const FOOTER_INJECT = getEnv(import.meta.env, Astro, 'FOOTER_INJECT')
{...seoParams}
/>
<Fragment set:html={HEADER_INJECT} />
</head>
<script src="src/lib/backToTop.js" type="module"></script></head
>
<body>
<div id="wrapper">
<div id="container">
@@ -123,7 +125,19 @@ const FOOTER_INJECT = getEnv(import.meta.env, Astro, 'FOOTER_INJECT')
</div>
</div>
</div>
<button id="back-to-top" aria-label="Back to top" title="Back to top">
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<polyline points="18 15 12 9 6 15"></polyline>
</svg>
</button>
<Fragment set:html={FOOTER_INJECT} />
</body>
</html>

23
src/lib/backToTop.js Normal file
View File

@@ -0,0 +1,23 @@
function setupBackToTop() {
const backToTopButton = document.querySelector('#back-to-top')
// Toggle button visibility based on scroll position
const toggleBackToTopButton = () => {
backToTopButton.style.display = window.scrollY > 300 ? 'flex' : 'none'
}
// Attach scroll event listener to window
window.addEventListener('scroll', toggleBackToTopButton)
toggleBackToTopButton() // Initial check for button visibility
// Smooth scroll to top when button is clicked
backToTopButton.addEventListener('click', () => {
window.scrollTo({
top: 0,
behavior: 'smooth',
})
})
}
// Initialize the functionality once page is fully loaded
document.addEventListener('DOMContentLoaded', setupBackToTop)