vue2中添加top回到顶部功能丝滑动画

956 阅读2分钟

1.需要简单的滚动动画建议先给全局添加css样式 scroll-behavior: smooth

html,
body {
	scroll-behavior: smooth;
}

2.滚动置顶

document.scrollingElement.scrollTop = 0;
// or window.scrollTo(0, 0);

3.以下还有这些方法

 .scroll()、 .scrollTo()、 .scrollBy()、 .scrollIntoView()

4.同样,几个有关滚动的js方法也可以添加类似 scroll-behavior: smooth 的参数已达到平滑滚动效果 —— scroll、scrollTo、scrollBy、scrollIntoView(scrollIntoView 稍有不同,下面会单独说)。

scroll(x, y)、 scrollTo(x, y)、 scrollBy(x, y)标识分别沿着x和y轴滚动的距离。

它们还都可以以一个scrollOptions对象作为参数,

scrollOptions = {
  	top: 0,
  	left: 0,
  	behavior: 'smooth' //平滑滚动
};
scroll(scrollOptions)
//scroll({
//    top:0,
//    left:0,
//    behavior:smooth
//})
this.scrollWrapper.scrollTo({
	top: this.queryParams.top,
	left: this.queryParams.left,
	behavior: this.queryParams.smooth ? 'smooth' : 'auto'
});

 .scrollIntoView()

element.scrollIntoView(alignToTop);
element.scrollIntoView({
	block: 'start' | 'end' | 'center' | 'nearest', 
	inline: 'start' | 'end' | 'center' | 'nearest', 
	behavior: 'smooth' | 'auto'
});
  • alignToTop 一个Boolean值
  • true,默认值,相当于 scrollIntoViewOptions: {block: 'start', inline: 'nearest'},元素的顶端将和其所在滚动区的可视区域的顶端对齐
  • false,相当于 scrollIntoViewOptions: {block: 'end', inline: 'nearest'},元素的底端将和其所在滚动区的可视区域的底端对齐

overscroll-behavior: contain;

多滚动区域,滚动不传播。css

overscroll-behavior: contain | auto | none;
overscroll-behavior-x: contain | auto | none;
overscroll-behavior-y: contain | auto | none;
  • auto - 默认。元素的滚动会传播给祖先元素。
  • contain - 阻止滚动链接,滚动不会传播给祖先。
  • none - 和 contain 效果一样。

滚动溢出是会有一段变慢的,影响体验

只需要加一行代码:css

overscroll-behavior: contain;

在此之前,张鑫旭大大就已经试图用js解决这个问题,点这里

history.scrollRestoration

设置返回页面是否返回原滚动位置

在从页面跳转回来的时候,一般浏览器都会“贴心”地返回到该页面原来的滚动位置,该行为由 history.scrollRestoration 属性控制的,默认是“auto”,

若不想回到原来的位置,可将值设为“manual”,手动,即不返回原位置,而是手动返回,此时浏览器会返回到页面顶部。但据测试,“返回”都是瞬间的,即使设置了 scroll-behavior: smooth 也无效。

if ('scrollRestoration' in history) {
  	history.scrollRestoration = 'manual';
}

最后说一下

如果这些代码没有进行回到顶部,说明你此时的容器其实相对于窗口没有进行滚动,比如你的body或者#app元素被写死了高度,实际上你的滚动都只是在这两个容器中的元素,window其实反应了,只是你的父容器只有视窗大小,所有会觉得没有效果

解决办法:

vue中用

      this.$refs.xxx.scrollIntoView({
        block: 'start',
        inline: 'nearest',
        behavior: 'smooth'
      });

xxx为你获取元素实例,方法会按照你获取的元素让其对视窗对齐

  <div ref="xxx"></div>

如果之前为我的建议设置了css可以这样写

//     this.$refs.xxx.scrollIntoView({
//       block: 'start',
//        inline: 'nearest'
//      });
//或者
this.$refs.xxx.scrollIntoView(true);
//true为至顶,false为至底

希望这篇文章可以解决你的问题

up萌新,第一次,别喷太凶