export class BackToTop {
    /*
     * 返回顶部按钮
     * */
    private readonly _button: HTMLElement = document.getElementById('back-to-top');

    /**
     * 滚动阈值(像素)
     */
    private readonly _threshold: number = 300;

    constructor() {
        if (!this._button) {
            return;
        }
        this.init();
    }

    private init(): void {
        this.bindEvents();
        // 检查初始状态
        this.checkScroll();
    }

    private bindEvents(): void {
        // 节流滚动处理
        let ticking = false;
        window.addEventListener('scroll', () => {
            if (!ticking) {
                window.requestAnimationFrame(() => {
                    this.checkScroll();
                    ticking = false;
                });
                ticking = true;
            }
        });

        // 点击事件处理
        this._button?.addEventListener('click', (e) => {
            e.preventDefault();
            this.scrollToTop();
        });
    }

    private checkScroll(): void {
        if (window.scrollY > this._threshold) {
            this._button?.classList.add('is-visible');
        } else {
            this._button?.classList.remove('is-visible');
        }
    }

    private scrollToTop(): void {
        window.scrollTo({
            top: 0,
            behavior: 'smooth',
        });
    }
}
⚠⚠    以下内容为AI分析的结果,请根据实际情况进行判断。

这是一个用 TypeScript 编写的"返回顶部"功能类,实现了网页中常见的回到页面顶部按钮功能。让我详细解释一下代码的各个部分:

类结构和属性

export class BackToTop {
    private readonly _button: HTMLElement = document.getElementById('back-to-top');
    private readonly _threshold: number = 300;
  • _button:获取页面中 ID 为 'back-to-top' 的 DOM 元素
  • _threshold:滚动阈值,设置为 300 像素,用于控制按钮显示时机

构造函数

constructor() {
    if (!this._button) {
        return;
    }
    this.init();
}
  • 检查按钮元素是否存在,如果不存在则直接返回
  • 如果存在则调用初始化方法

初始化方法

private init(): void {
    this.bindEvents();
    this.checkScroll();
}
  • 绑定事件监听器
  • 检查初始滚动状态

事件绑定

private bindEvents(): void {
    // 滚动事件处理(使用节流优化)
    let ticking = false;
    window.addEventListener('scroll', () => {
        if (!ticking) {
            window.requestAnimationFrame(() => {
                this.checkScroll();
                ticking = false;
            });
            ticking = true;
        }
    });

    // 点击事件处理
    this._button?.addEventListener('click', (e) => {
        e.preventDefault();
        this.scrollToTop();
    });
}

滚动事件优化

  • 使用 requestAnimationFrameticking 标志实现节流
  • 避免滚动事件频繁触发导致的性能问题

点击事件

  • 阻止默认行为
  • 调用滚动到顶部的方法

滚动检查

private checkScroll(): void {
    if (window.scrollY > this._threshold) {
        this._button?.classList.add('is-visible');
    } else {
        this._button?.classList.remove('is-visible');
    }
}
  • 检查当前滚动位置
  • 超过阈值(300px)时添加 is-visible 类名显示按钮
  • 否则移除类名隐藏按钮

滚动到顶部

private scrollToTop(): void {
    window.scrollTo({
        top: 0,
        behavior: 'smooth',
    });
}
  • 使用原生 scrollTo API
  • behavior: 'smooth' 实现平滑滚动效果

使用方式

// 在页面加载后实例化
const backToTop = new BackToTop();

配套 CSS 示例

#back-to-top {
    position: fixed;
    bottom: 20px;
    right: 20px;
    opacity: 0;
    visibility: hidden;
    transition: all 0.3s ease;
}

#back-to-top.is-visible {
    opacity: 1;
    visibility: visible;
}

这个类设计得很好,具有以下特点:

  • 性能优化:使用节流避免频繁的滚动事件处理
  • 容错处理:检查 DOM 元素是否存在
  • 用户体验:平滑滚动效果
  • 可维护性:清晰的代码结构和职责分离
评论加载中...