/**
* Back To Top Component
* Handles the visibility and scroll behavior of the back-to-top button
*/
export class BackToTop {
constructor() {
this.button = document.getElementById('back-to-top');
this.threshold = 300; // Scroll threshold in pixels
if (!this.button) return;
this.init();
}
init() {
this.bindEvents();
this.checkScroll(); // Check initial state
}
bindEvents() {
// Throttled scroll handler
let ticking = false;
window.addEventListener('scroll', () => {
if (!ticking) {
window.requestAnimationFrame(() => {
this.checkScroll();
ticking = false;
});
ticking = true;
}
});
// Click handler
this.button.addEventListener('click', (e) => {
e.preventDefault();
this.scrollToTop();
});
}
checkScroll() {
if (window.scrollY > this.threshold) {
this.button.classList.add('is-visible');
} else {
this.button.classList.remove('is-visible');
}
}
scrollToTop() {
window.scrollTo({
top: 0,
behavior: 'smooth'
});
}
}
⚠⚠ 以下内容为AI分析的结果,请根据实际情况进行判断。
这段代码实现了一个“返回顶部(Back to Top)”组件,主要负责在用户滚动到一定距离后显示一个按钮,并在点击该按钮时平滑滚动回到页面顶部。下面按逻辑分块解释:
总体行为
- 在页面有一个 id 为 back-to-top 的元素时才会生效;若不存在则构造函数立即返回,不做任何事。
- 当页面垂直滚动超过 threshold(默认 300 像素)时,会给该按钮添加 CSS 类 is-visible,使其可见;否则移除该类使其隐藏。
- 点击按钮会阻止默认行为,并调用 scrollToTop() 使用浏览器的平滑滚动回到顶部。
构造与初始化
- constructor(): 获取按钮元素并设置阈值 threshold;如果找不到按钮直接返回,否则调用 init()。
- init(): 绑定事件并调用 checkScroll() 做一次初始状态检查(页面加载时就会正确显示/隐藏按钮)。
事件绑定(bindEvents)
- 为 window 的 scroll 事件注册处理器,但使用了基于 requestAnimationFrame 的节流(ticking 变量):
- ticking 用来避免在一次 rAF 完成之前重复注册执行,保证 scroll 处理最多以浏览器刷新率执行一次,从而减小性能开销。
- 为按钮注册 click 事件:阻止默认行为并执行平滑滚动。
滚动检查(checkScroll)
- 读取 window.scrollY,如果大于 threshold 则添加 is-visible,否则移除该类。CSS 负责控制显示/隐藏或动画。
滚动到顶部(scrollToTop)
- 使用 window.scrollTo({ top: 0, behavior: 'smooth' }) 发起平滑滚动(注意:behavior: 'smooth' 在某些老旧浏览器中可能不被支持)。
补充说明(可选)
- 需要在样式表中定义 #back-to-top 及 .is-visible 的表现(例如 display、opacity、transition 等)。
- 若需兼容更老的浏览器,可考虑为 smooth 滚动和 requestAnimationFrame 提供 polyfill,或使用自定义动画函数。
- 可进一步增强可访问性(如键盘焦点、aria-label 等)。
评论加载中...