由于scrollTop是js属性设置,所以css的属性基本无法为滚动条设置过渡效果,但是有一个css属性可以完成一点效果。
scroll-behavior: smooth;
当增加这一css的后,会发现效果变得生硬,完全用不了啊!
网络上通常的解决方法是写一个滚动函数:
scrolling (el, duration, targetOffsetTop) {
// 获取当前滚动位置
let currentScrollTop = el.scrollTop;
// 计算滚动距离
let distance = targetOffsetTop - currentScrollTop;
// 计算每一帧滚动的距离和时间间隔
let scrollStep = Math.PI / (duration / 15);
let cosParameter = (targetOffsetTop - currentScrollTop) / 2;
let scrollCount = 0;
let scrollMargin;
// 定义滚动动画函数
function smoothScroll() {
// 设置下一帧滚动位置
let targetScrollTop = currentScrollTop + cosParameter - cosParameter * Math.cos(scrollCount * scrollStep);
el.scrollTop = targetScrollTop;
// 更新滚动计数器和滚动边距
scrollCount++;
scrollMargin = distance - cosParameter + cosParameter * Math.cos(scrollCount * scrollStep);
// 判断是否继续滚动
if (Math.abs(scrollMargin) > 0.2) {
requestAnimationFrame(smoothScroll);
}
}
// 调用滚动动画函数
smoothScroll();
}
当然肯定有更好的办法,如果你不考虑怎么去过渡:
el.scrollTo({top: 0, behavior: 'smooth'})
其中, top指定距离顶部的位置是多少,behavior是滚动方式,这样写完发现效果实现了!
补丁
最近遇到了横向滚动,点击菜单会添加这一项的标签,一直在通过各种距离想让滚动条滚动到对应的标签附近,结果很失败,查了一些方法,发现是我无知了
this.$refs.activeItem[0].scrollIntoView({ behavior: "smooth", inline: "center" });
ok 只需要一个scrollIntoView
方法,只需要找到激活的标签,然后调用方法,看来得恶补下基础知识了。