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

如何调整overflow: scroll滚动速度?延长跳转至下方<div>的时长

调整overflow容器内平滑滚动的时长

如果你用的是原生scrollIntoView({behavior: 'smooth'})或依赖scroll-behavior: smooth的CSS属性,浏览器会默认控制滚动时长(通常0.3-0.5秒),没法直接自定义。要实现2秒或3秒的滚动时长,得用JavaScript手动控制滚动动画。

实现步骤:

  • 获取滚动容器和目标元素
  • 计算需要滚动的距离(容器scrollTop到目标元素相对容器顶部的偏移量)
  • 用requestAnimationFrame实现逐帧滚动,按设定总时长控制滚动速度

代码示例(垂直滚动):

// 获取对应元素
const scrollContainer = document.getElementById('your-scroll-container');
const targetDiv = document.getElementById('target-div');
const scrollButton = document.getElementById('scroll-button');

// 自定义滚动函数:容器、目标元素、总时长(毫秒)
function smoothScrollTo(container, target, duration) {
  const targetOffset = target.offsetTop - container.offsetTop;
  const startScrollTop = container.scrollTop;
  const distance = targetOffset - startScrollTop;
  let startTime = null;

  function animation(currentTime) {
    if (!startTime) startTime = currentTime;
    const timeElapsed = currentTime - startTime;
    const progress = Math.min(timeElapsed / duration, 1);
    
    // 可选:ease-in-out缓动让滚动更自然,要匀速直接用progress即可
    const easeProgress = progress < 0.5 
      ? 2 * progress * progress 
      : 1 - Math.pow(-2 * progress + 2, 2) / 2;
    
    container.scrollTop = startScrollTop + distance * easeProgress;
    
    if (timeElapsed < duration) {
      requestAnimationFrame(animation);
    }
  }

  requestAnimationFrame(animation);
}

// 绑定按钮点击事件
scrollButton.addEventListener('click', () => {
  // 设置为2000毫秒(2秒),可改为3000实现3秒滚动
  smoothScrollTo(scrollContainer, targetDiv, 2000);
});

补充说明:

  • 替换代码中的your-scroll-container、target-div、scroll-button为你实际的元素ID
  • 若需水平滚动,将scrollTop替换为scrollLeft,offsetTop替换为offsetLeft

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 08:55:22