基于JS实现回到页面顶部的五种写法(从实现到增(2)

<script> var timer = null; box.onclick = function(){ cancelAnimationFrame(timer); timer = requestAnimationFrame(function fn(){ var oTop = document.body.scrollTop || document.documentElement.scrollTop; if(oTop > 0){ scrollTo(0,oTop-50); timer = requestAnimationFrame(fn); }else{ cancelAnimationFrame(timer); } }); } </script>

  3、增加scrollBy()动画效果

  将scrollBy(x,y)中的y参数设置为-50,直到scrollTop为0,则回滚停止

<script> var timer = null; box.onclick = function(){ cancelAnimationFrame(timer); timer = requestAnimationFrame(function fn(){ var oTop = document.body.scrollTop || document.documentElement.scrollTop; if(oTop > 0){ scrollBy(0,-50); timer = requestAnimationFrame(fn); }else{ cancelAnimationFrame(timer); } }); } </script>

实现

  由于scrollTop、scrollBy()和scrollTo()方法,都以scrollTop值是否减少为0作为动画停止的参照,且三个动画的原理和实现都基本相似,性能也相似。最终,以最常用的scrollTop属性实现动画增强效果

  当然,如果觉得50的速度不合适,可以根据实际情况进行调整

<style> .box{ position:fixed; right:10px; bottom: 10px; height:30px; width: 50px; text-align:center; padding-top:20px; background-color: lightblue; border-radius: 20%; overflow: hidden; } .box:hover:before{ top:50% } .box:hover .box-in{ visibility: hidden; } .box:before{ position: absolute; top: -50%; left: 50%; transform: translate(-50%,-50%); content:'回到顶部'; width: 40px; color:peru; font-weight:bold; } .box-in{ visibility: visible; display:inline-block; height:20px; width: 20px; border: 3px solid black; border-color: white transparent transparent white; transform:rotate(45deg); } </style> <body> <div> <div></div> </div> </body> <script> var timer = null; box.onclick = function(){ cancelAnimationFrame(timer); timer = requestAnimationFrame(function fn(){ var oTop = document.body.scrollTop || document.documentElement.scrollTop; if(oTop > 0){ document.body.scrollTop = document.documentElement.scrollTop = oTop - 50; timer = requestAnimationFrame(fn); }else{ cancelAnimationFrame(timer); } }); } </script>

以上所述是小编给大家介绍的基于JS实现回到页面顶部的五种写法(从实现到增强)的全部叙述,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的,在此也非常感谢大家对脚本之家网站的支持!

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wzfgwj.html