blog / src /components /controls /BackToTop.astro
cacode's picture
Upload 434 files
96dd062 verified
---
import FloatingButton from "@/components/common/FloatingButton.astro";
---
<!-- There can't be a filter on parent element, or it will break `fixed` -->
<FloatingButton
id="back-to-top-btn"
icon="material-symbols:keyboard-arrow-up-rounded"
ariaLabel="Back to Top"
onclick="backToTop()"
class="hide"
/>
<script is:raw is:inline>
function backToTop() {
// 直接使用原生滚动,避免OverlayScrollbars冲突
window.scroll({ top: 0, behavior: "smooth" });
}
// 响应式返回顶部按钮管理器
if (typeof window.BackToTopManager === "undefined") {
window.BackToTopManager = class BackToTopManager {
constructor() {
this.button = document.getElementById("back-to-top-btn");
this.init();
}
init() {
if (!this.button) return; // wrapper checks removed as it is now flexible
this.setupScrollListener();
}
setupScrollListener() {
const updateVisibility = () => {
const scrollTop =
window.pageYOffset || document.documentElement.scrollTop;
// 当滚动超过200px时显示按钮
if (scrollTop > 200) {
this.button.classList.remove("hide");
} else {
this.button.classList.add("hide");
}
};
window.addEventListener("scroll", updateVisibility, { passive: true });
}
};
}
// ... existing initialization logic ...
// 页面加载完成后初始化
document.addEventListener("DOMContentLoaded", () => {
new BackToTopManager();
});
// 如果页面已经加载完成,立即初始化
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", () => {
new BackToTopManager();
});
} else {
new BackToTopManager();
}
</script>