java返回页面顶部代码_前端 平滑滚动到底部/顶部

页面滚动时,添加平滑特效

1.在页面入口处,添加css

1 html{

2 scroll-behavior:smooth;

3 }

添加全局css之后,直接使用window.scroll(0,0)就可以平滑滚动到顶部了。

注:兼容性很差,仅支持火狐、chrome高级版本

c56d1220b7f495fe90fce2bac14d4724.png

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全局的设置删除了,否则滚动会很缓慢。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值