jquery animate scrolltop callback

蹲街弑〆低调 提交于 2019-12-10 23:05:32

问题


I have the following jquery that scrolls the page to the top, then performs a callback function.

The problem is that even if the page is already at the top, it still waits for the '1000' to elapse before performing the callback, which i dont want it to.

$('html').animate({scrollTop:0}, 1000, 'swing', function(){

//do something

});

回答1:


It doesn't wait

It animates your document from top to the top... Funny but that's how it is. You have other alternatives. Either:

  • check your page position before scrolling (as others suggested by providing some code) or
  • use some jQuery plugin that works differently

My .scrollintoview() jQuery plugin works that way. It scrolls only if it has to and runs a complete handler after scrolling is complete (if there was scrolling in the first place) or immediately if scrolling is not needed.

But it needs some element that needs to be scrolled. You're actually not scrolling any element into view but rather just HTML. This is of course not the safest way. It's better to use either:

$("html,body")

or

$(window)

It's more cross browser supported. So your $("html") may not work in all of them.




回答2:


var html=$('html');
if(html.scrollTop()>0){
  html.animate({scrollTop:0}, 1000, 'swing', function(){
  //do something
});
}else{
  //do something
}



回答3:


if( $(window).scrollTop() > 0 ) {
    $('html').animate({scrollTop:0}, 1000, 'swing', function(){

        //callback after animate

    });
} else {
    // callback right now (no wait)
}


来源:https://stackoverflow.com/questions/6206738/jquery-animate-scrolltop-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!