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

2019-01-18 02:58发布

Right now I'm using this:

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

which doesn't work in Chrome, and in Opera I get a small flicker: the browser instantly scrolls to the top, then back to the bottom and then it begins to scroll slowly back to top, like it should.

Is there a better way to do this?

8条回答
Explosion°爆炸
2楼-- · 2019-01-18 03:57

maybe something like

$('body').animate({scrollTop:0}, 'slow');

aswell as the html one.

edit >

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

should cover all browsers!

查看更多
时光不老,我们不散
3楼-- · 2019-01-18 04:01
$(window).animate({ scrollTop: 0 }, 'slow');

It works cross-browser

查看更多
登录 后发表回答