jQuery .scrollTop(); +animation

当单击button时,我将页面设置为滚动到顶部。 但是,首先我使用if语句来查看页面顶部是否未设置为0.然后,如果不是0,则使页面动起来滚动到顶部。

var body = $("body"); var top = body.scrollTop() // Get position of the body if(top!=0) { body.animate({scrollTop:0}, '500'); } 

现在棘手的部分是animation页面滚动到顶部后的东西。 所以我的下一个想法是,找出页面的位置是什么。 所以我使用控制台日志来查明。

 console.log(top); // the result was 365 

这给了我365的结果,我猜这是我在滚动到顶部之前的位置号。

我的问题是如何将位置设置为0,以便我可以添加另一个页面在0时运行的animation?

谢谢!

为此,可以为滚动animation完成后执行的animate命令设置一个callback函数。

例如:

 var body = $("html, body"); body.stop().animate({scrollTop:0}, 500, 'swing', function() { alert("Finished animating"); }); 

在提醒代码的位置,您可以执行更多的JavaScript来添加进一步的animation。

此外,“摆动”在那里设置缓和。 查看http://api.jquery.com/animate/了解更多信息。;

试试这个代码:

 $('.Classname').click(function(){ $("html, body").animate({ scrollTop: 0 }, 600); return false; }); 

用这个:

 $('a[href^="#"]').on('click', function(event) { var target = $( $(this).attr('href') ); if( target.length ) { event.preventDefault(); $('html, body').animate({ scrollTop: target.offset().top }, 500); } }); 

试试这个:

 var body = $("body, html"); var top = body.scrollTop() // Get position of the body if(top!=0) { body.animate({scrollTop :0}, 500,function(){ //DO SOMETHING AFTER SCROLL ANIMATION COMPLETED alert('Hello'); }); } 

为此,您可以使用callback方法

 body.animate({ scrollTop:0 }, 500, function(){} // callback method use this space how you like ); 

带有点击function的代码()

  var body = $('html, body'); $('.toTop').click(function(e){ e.preventDefault(); body.animate({scrollTop:0}, 500, 'swing'); }); 

.toTop =被点击元素的类可能是imga

 jQuery("html,body").animate({scrollTop: jQuery("#your-elemm-id-where you want to scroll").offset().top-<some-number>}, 500, 'swing', function() { alert("Finished animating"); });