页面滚动时,添加平滑特效
1.在页面入口处,添加css
1 html{
2 scroll-behavior:smooth;
3 }
添加全局css之后,直接使用window.scroll(0,0)就可以平滑滚动到顶部了。
注:兼容性很差,仅支持火狐、chrome高级版本
2.指定滚动操作,使用平滑效果
1 let anchorElement = document.getElementById("softwareHeader-container");2 let scrollIntoViewOptions: ScrollIntoViewOptions ={
3 block:'end',4 behavior: "smooth"5 }
6 if (anchorElement){
7 anchorElement.scrollIntoView(scrollIntoViewOptions)8 }
1 let scrollOptions:ScrollToOptions ={
2 left:0,3 top: 1000,4 behavior:'smooth'5 }
6
7 window.scrollTo(scrollOptions);
兼容性:大部分支持,猎豹不支持。
3.添加JS滚动代码
滚动到顶部:
1 returnTop = () =>{2 //记录当前执行动画的标识
3 let animationStepNumber;4 functionexeucteAnimationByStep() {5 //当前页面的滚动高度
6 let currentScrollTop = document.documentElement.scrollTop ||document.body.scrollTop;7 if (currentScrollTop >= 4) {8 animationStepNumber =window.requestAnimationFrame(exeucteAnimationByStep);9 let scrollLocationChanging = currentScrollTop / 9;10 scrollLocationChanging = scrollLocationChanging > 1 ? scrollLocationChanging : 1;11 let newScrollTop = currentScrollTop -scrollLocationChanging;12 window.scrollTo(0, newScrollTop);13 } else{14 window.cancelAnimationFrame(animationStepNumber);15 window.scrollTo(0, 0);16 }17 }18 animationStepNumber =window.requestAnimationFrame(exeucteAnimationByStep);19 }
滚动到底部:
1 scrollToPageBottom = () =>{2 let animationStepNumber;3 functionexeucteAnimationByStep() {4 let currentScrollTop = document.documentElement.scrollTop ||document.body.scrollTop;5 let totalHeight = (document.documentElement.scrollHeight || document.body.scrollHeight) -window.innerHeight;6 //剩余的高度
7 let scrollingHeight = totalHeight -currentScrollTop;8 if (scrollingHeight >= 4) {9 animationStepNumber =window.requestAnimationFrame(exeucteAnimationByStep);10 //滚动变量
11 let scrollChangedHeight = scrollingHeight / 9;12 scrollChangedHeight = scrollChangedHeight > 1 ? scrollChangedHeight : 1;13 window.scrollTo(0, currentScrollTop +scrollChangedHeight);14 } else{15 window.cancelAnimationFrame(animationStepNumber);16 window.scrollTo(0, totalHeight);17 }18 }19 animationStepNumber =window.requestAnimationFrame(exeucteAnimationByStep);20 };
原理:
requestAnimationFrame,告诉浏览器重绘时执行动画,参数是具体执行方法,返回参数是nubmer(标识)
注:如果需要连续执行动画,则需要在回调函数中,先添加一个待执行动画回调requestAnimationFrame。(如上案例)
注:执行完所有动画后,一定要注销上一个动画回调(如果有的话),否则会影响页面滚动(因为回调函数中的动画委托还在待处理呢)。
兼容性:平滑效果,支持所有浏览器。
缺陷:滚动过程中,不能操作手动滚动页面。这个缺陷,也有理论上的解法,可以添加滚动事件监听,如果滚动方向与平滑动画效果方向相反,则取消平滑动画的处理(调cancelAnimationFrame即可)
特别提示:添加纯js平滑滚动方案,需要将第1个方案css全局的设置删除了,否则滚动会很缓慢。