jQuery cross-browser “scroll to top”, with animation

前端 未结 8 938
难免孤独
难免孤独 2020-12-09 09:32

Right now I\'m using this:

$(\'#go-to-top\').each(function(){
  $(this).click(function(){ 
    $(\'html\').animate({ scrollTop: 0 }, \'slow\'); return true;          


        
8条回答
  •  情深已故
    2020-12-09 09:53

    This will be working in all browsers. It avoids the hash tag on the url, so, the smooth scroll is done!

     $('#back-top a[href*=#]:not([href=#])').click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
    
          var target = $(this.hash);
          target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
          if (target.length) {
    
            $('html,body').animate({
    
              scrollTop: target.offset().top
            }, 1000);
            return false;
          }
        }
      }); 
    

提交回复
热议问题