当前位置:首页 > JavaScript

js 实现滚动

2026-01-15 14:38:49JavaScript

实现滚动的方法

使用 window.scrollTo()

window.scrollTo() 方法可以滚动到文档中的特定位置。可以指定 xy 坐标,或者使用平滑滚动的选项。

// 滚动到指定位置(x, y)
window.scrollTo(0, 500);

// 使用平滑滚动
window.scrollTo({
  top: 500,
  behavior: 'smooth'
});

使用 window.scrollBy()

window.scrollBy() 方法相对于当前滚动位置滚动指定的距离。

// 向下滚动 200 像素
window.scrollBy(0, 200);

// 平滑滚动 200 像素
window.scrollBy({
  top: 200,
  behavior: 'smooth'
});

使用 Element.scrollIntoView()

scrollIntoView() 方法可以让元素滚动到可视区域。支持平滑滚动选项。

const element = document.getElementById('target');
element.scrollIntoView({
  behavior: 'smooth',
  block: 'start' // 或 'center', 'end', 'nearest'
});

监听滚动事件

可以通过监听 scroll 事件来执行滚动相关的逻辑。

window.addEventListener('scroll', () => {
  console.log('当前滚动位置:', window.scrollY);
});

使用 requestAnimationFrame 实现自定义动画

如果需要更复杂的滚动动画,可以使用 requestAnimationFrame 逐帧控制滚动。

function smoothScrollTo(targetY, duration = 1000) {
  const startY = window.scrollY;
  const distance = targetY - startY;
  const startTime = performance.now();

  function scrollStep(timestamp) {
    const elapsed = timestamp - startTime;
    const progress = Math.min(elapsed / duration, 1);
    window.scrollTo(0, startY + distance * progress);

    if (progress < 1) {
      requestAnimationFrame(scrollStep);
    }
  }

  requestAnimationFrame(scrollStep);
}

// 调用自定义滚动函数
smoothScrollTo(1000, 1500);

滚动到页面顶部或底部

可以使用 scrollToscrollIntoView 快速滚动到页面顶部或底部。

// 滚动到顶部
window.scrollTo({
  top: 0,
  behavior: 'smooth'
});

// 滚动到底部
window.scrollTo({
  top: document.body.scrollHeight,
  behavior: 'smooth'
});

js 实现滚动

标签: js
分享给朋友:

相关文章

js实现拷贝

js实现拷贝

实现文本拷贝 使用 document.execCommand 方法(已废弃但兼容性较好): function copyText(text) { const textarea = documen…

js分组实现

js分组实现

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

js类实现

js类实现

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

js手势实现

js手势实现

手势识别实现方法 在JavaScript中实现手势识别通常涉及监听触摸事件(touchstart、touchmove、touchend)或鼠标事件(mousedown、mousemove、mouseu…

js钟表实现

js钟表实现

实现JavaScript钟表的基本方法 创建一个简单的JavaScript钟表可以通过以下步骤完成,涵盖数字和模拟两种形式。 数字钟表实现 HTML结构只需一个显示时间的容器: <div i…

js实现滚动

js实现滚动

实现滚动效果的方法 在JavaScript中实现滚动效果可以通过多种方式完成,以下是一些常见的方法: 使用window.scrollTo() window.scrollTo()方法可以将页面滚动到…