平滑滚动到顶部

1,004 阅读1分钟

scroll-behavior

示例:

html {
  scroll-behavior: auto|smooth|initial|inherit
}

注意: IE不支持

window.scrollTo

window.scrollTo(x-coord, y-coord);
window.scrollTo(options);

示例

window.scrollTo(x, y);
window.scrollTo({ left: 0, top: 0, behavior: "smooth" });

注意:

IE不支持ScrollToOptions
Safari does not have support for the smooth scroll behavior

scrollIntoView

让当前的元素滚动到浏览器窗口的可视区域内。这是一个实验中的功能。

语法

element.scrollIntoView(); // 等同于element.scrollIntoView(true) 
element.scrollIntoView(alignToTop); // Boolean型参数 true:{block: "start", inline: "nearest"}.
element.scrollIntoView(scrollIntoViewOptions); // Object型参数 

示例

document.documentElement.scrollIntoView({block: 'start', behavior: 'smooth'});

注意

Safari No support for smooth behavior or center options
IE 不支持传Object型参数

requestAnimationFrame

window.requestAnimationFrame() 告诉浏览器——你希望执行一个动画,并且要求浏览器在下次重绘之前调用指定的回调函数更新动画。该方法需要传入一个回调函数作为参数,该回调函数会在浏览器下一次重绘之前执行

window.requestAnimationFrame(callback);

示例

function toTop(position) {
  // 获取当前元素滚动的距离
  let scrollTopDistance = document.documentElement.scrollTop || document.body.scrollTop;
  const smoothScroll = () => {
    let distance = position - scrollTopDistance;
    // 每次滚动的距离要不一样,制造一个缓冲效果
    scrollTopDistance = scrollTopDistance + distance / 5;
    if (Math.abs(distance) < 1) {
      document.documentElement.scrollTop = position;
    } else {
      document.documentElement.scrollTop = scrollTopDistance;
      requestAnimationFrame(smoothScroll);
    }
  };
  requestAnimationFrame(smoothScroll);
}

requestAnimationFrame和setTimeout有点相似,不同之处在于,setTimeout是在等待指定毫秒数之后被调用,而requestAnimationFrame则是在每次屏幕被刷新时被调用,注意,这里的屏幕刷新并不是指页面被刷新。requestAnimationFrame方法仅有一个参数,传入的这个方法将会在下一次屏幕刷新时被调用。requestAnimationFrame的随系统的刷新频率被调用的特性使其非常适合用来做动画以及优化页面的性能。

总结

对于不需要那么丝滑的情况,可以使用最简单的方式scrollTop 或者 window.scrollTo(x, y),如扩考虑如德芙般丝滑,requestAnimationFrame为首选。