You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

原生JS锚点滚动优化需求:滚动生硬过快,需更平滑缓慢

自定义平滑锚点滚动实现方案

原生scrollIntoView({behavior: 'smooth'})的滚动速度由浏览器默认控制,无法直接调整。想要更慢、更自然的滚动效果,你可以替换成自定义的滚动动画代码,精准控制速度和缓动逻辑:

document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();
        const targetId = this.getAttribute('href');
        const targetElement = document.querySelector(targetId);
        if (!targetElement) return;

        // 自定义滚动时长(单位:毫秒,数值越大滚动越慢)
        const duration = 1200;
        const startY = window.scrollY;
        const targetY = targetElement.getBoundingClientRect().top + startY;
        const distance = targetY - startY;
        let startTime = null;

        function scrollAnimation(currentTime) {
            if (!startTime) startTime = currentTime;
            const timeElapsed = currentTime - startTime;
            // 计算滚动进度,最大不超过1
            const progress = Math.min(timeElapsed / duration, 1);
            
            // 用ease-in-out缓动函数,让滚动开头和结尾更平缓
            const easeProgress = progress < 0.5 
                ? 2 * progress * progress 
                : 1 - Math.pow(-2 * progress + 2, 2) / 2;
            
            window.scrollTo(0, startY + distance * easeProgress);
            
            // 未完成时长则继续动画
            if (timeElapsed < duration) {
                requestAnimationFrame(scrollAnimation);
            }
        }

        requestAnimationFrame(scrollAnimation);
    });
});

关键调整说明

  • 滚动速度控制:修改duration的值即可调整快慢,比如设置1500就是1.5秒完成滚动,按需修改即可
  • 缓动效果优化:加入ease-in-out缓动逻辑,避免匀速滚动的生硬感,让滚动过程更顺滑
  • 容错处理:增加目标元素不存在时的判断,避免控制台报错

内容的提问来源于stack exchange,提问作者JoaMika

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 17:35:01