MST

星途 面试题库

面试题:JavaScript中如何实现平滑滚动到文档特定锚点

请使用JavaScript编写一个函数,该函数接收一个锚点的id作为参数,实现平滑滚动到该锚点位置,并且要兼容常见浏览器。
16.4万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试
function smoothScrollToAnchor(anchorId) {
    const target = document.getElementById(anchorId);
    if (target) {
        if (window.requestAnimationFrame) {
            let start = null;
            const scroll = (timestamp) => {
                if (!start) start = timestamp;
                const progress = timestamp - start;
                const easeInOutQuad = (t) => t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
                const scrollTop = target.offsetTop * easeInOutQuad(progress / 1000);
                window.scrollTo(0, scrollTop);
                if (progress < 1000) {
                    window.requestAnimationFrame(scroll);
                }
            };
            window.requestAnimationFrame(scroll);
        } else {
            const targetTop = target.offsetTop;
            const step = targetTop / 20;
            let currentTop = window.pageYOffset;
            const timer = setInterval(() => {
                currentTop += step;
                if ((step > 0 && currentTop >= targetTop) || (step < 0 && currentTop <= targetTop)) {
                    clearInterval(timer);
                    window.scrollTo(0, targetTop);
                } else {
                    window.scrollTo(0, currentTop);
                }
            }, 50);
        }
    }
}