点击缓慢滑动返回顶部

版权声明:本文为博主原创文章,转载请注明出处: https://blog.csdn.net/weixin_43720095/article/details/84207935

点击缓慢滑动返回顶部

返回顶部组件是一种极其常见的网页功能,需求简单:页面滚动一定距离后,显示返回顶部的按钮,点击该按钮可以将滚动条滚回至页面开始的位置。

  1. 使用setinerval实现缓慢返回顶部
  //核心js代码
   var top=document.getElementById("backTop");
   var bottom=document.getElementById("backTop");
   top.onclick=function(){
       //alert(11);
       timer=setInterval(function(){
           var scrollTop=document.documentElement.scrollTop||document.body.scrollTop;
           var ispeed=Math.floor(-scrollTop/6);
           console.log(ispeed)
           if(scrollTop==0){
               clearInterval(timer);
           }
           document.documentElement.scrollTop=document.body.scrollTop=scrollTop+ispeed;
       },30)
   };

使用添加id=“backTop” 。

  1. 使用Javascript Scroll函数缓慢返回顶部
function backTop() {
  window.scrollBy(0,-100);
  scrolldelay=setTimeout('backTop()',100);
  if(document.documentElement.scrollTop==0)clearTimeout(scrolldelay);
 }

使用时onclick=“backTopl();”。

  1. 使用onload加上scroll功能实现缓慢返回顶部
BackTop=function(btnId){
  var btn=document.getElementById(btnId);
  var page=document.documentElement;
  window.onscroll=set;
  btn.onclick=function(){
   btn.style.display="none";
   window.onscroll=null;
   this.timer=setInterval(function(){
    page.scrollTop-=Math.ceil(page.scrollTop*0.1);
    if(page.scrollTop==0)clearInterval(btn.timer,window.onscroll=set);
   },10);
  };
  function set(){
   btn.style.display=page.scrollTop?'block':"none"}
  };
  BackTop('backTop');

使用时添加id=“backTop” 。

  1. 使用jquery插件实现缓慢返回顶部
    下载链接(内含说明)
    http://www.jq22.com/jquery-info325
    js部分:
$(function(){   
    $(window).scroll(function() {      
        if($(window).scrollTop() >= 100){
            $('.actGotop').fadeIn(300); 
        }else{    
            $('.actGotop').fadeOut(300);    
        }  
    });
    $('.actGotop').click(function(){
    $('html,body').animate({scrollTop: '0px'}, 800);});   
});
  1. 使用jquery动画缓慢返回顶部
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
 <script type="text/javascript">
  $("a").click(function(){
   $('html,body').animate({'scrollTop':'0'},500,)
  })
 </script>

猜你喜欢

转载自blog.csdn.net/weixin_43720095/article/details/84207935