当前位置:首页 > JavaScript

js实现一秒滚动的效果

2026-01-31 11:45:31JavaScript

使用 window.scrollBy 实现平滑滚动

通过 window.scrollBy 方法结合 requestAnimationFrame 实现平滑滚动效果。该方法逐帧调整滚动位置,形成动画效果。

function smoothScrollBy(distance, duration) {
  const start = window.pageYOffset;
  const startTime = performance.now();

  function scrollStep(timestamp) {
    const elapsed = timestamp - startTime;
    const progress = Math.min(elapsed / duration, 1);
    window.scrollBy(0, distance * progress - (window.pageYOffset - start));
    if (progress < 1) {
      requestAnimationFrame(scrollStep);
    }
  }

  requestAnimationFrame(scrollStep);
}

// 调用示例:每秒滚动100像素
smoothScrollBy(100, 1000);

使用 CSS scroll-behavior 属性

通过 CSS 的 scroll-behavior: smooth 属性实现原生平滑滚动效果,再通过 JavaScript 触发滚动。

<style>
  html {
    scroll-behavior: smooth;
  }
</style>

<script>
  function scrollPerSecond() {
    const currentPosition = window.pageYOffset;
    window.scrollTo(0, currentPosition + 100);
    setTimeout(scrollPerSecond, 1000);
  }
  scrollPerSecond();
</script>

使用 Element.scrollIntoView 方法

通过循环调用 scrollIntoView 方法实现逐元素滚动效果。

let currentElement = document.body.firstElementChild;

function scrollNextElement() {
  if (currentElement) {
    currentElement.scrollIntoView({ behavior: 'smooth' });
    currentElement = currentElement.nextElementSibling;
    setTimeout(scrollNextElement, 1000);
  }
}

scrollNextElement();

使用第三方库(如 SmoothScroll)

引入第三方库实现更复杂的滚动效果,例如 smooth-scroll 库。

<script src="https://cdn.jsdelivr.net/npm/smooth-scroll@16.1.3/dist/smooth-scroll.polyfills.min.js"></script>
<script>
  const scroll = new SmoothScroll();
  let currentPosition = 0;

  function autoScroll() {
    currentPosition += 100;
    scroll.animateScroll(currentPosition);
    setTimeout(autoScroll, 1000);
  }

  autoScroll();
</script>

注意事项

  • 移动端设备可能需要处理触摸事件冲突
  • 长时间运行的滚动需要添加终止条件
  • 性能敏感场景建议使用 requestAnimationFrame
  • 某些浏览器可能需要 polyfill 来支持平滑滚动 API

以上方法均可实现每秒自动滚动效果,可根据具体需求选择简单 CSS 方案或更可控的 JavaScript 动画方案。

js实现一秒滚动的效果

标签: 效果js
分享给朋友:

相关文章

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 或直接使用 window.location 实现页面跳转,适用于普通跳转或带参数的 URL。 // 方…

vue实现预览效果

vue实现预览效果

Vue 实现预览效果的方法 使用 v-html 指令实现简单预览 在 Vue 中可以通过 v-html 指令直接将 HTML 字符串渲染到页面上,适用于简单的富文本预览场景。 <templa…

js分组实现

js分组实现

分组实现方法 在JavaScript中,可以通过多种方式实现数组或对象的分组操作。以下是几种常见的方法: 使用Array.prototype.reduce() 通过reduce方法可以轻松实现数组…

vue实现框架效果

vue实现框架效果

Vue实现框架效果的方法 使用Vue实现框架效果可以通过多种方式完成,包括使用Vue Router、动态组件或第三方UI库。以下是几种常见的方法: 使用Vue Router实现布局框架 Vue Ro…

js类实现

js类实现

使用类实现 JavaScript 功能 在 JavaScript 中,类(Class)是一种语法糖,基于原型继承机制。通过 class 关键字可以更直观地定义对象模板。 基本类定义 class…

js实现选题

js实现选题

实现选题功能的JavaScript方法 基础实现方案 使用数组存储选项,通过随机索引选取: const options = ['选项A', '选项B', '选项C', '选项D']; const r…