Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
873 views
in Technique[技术] by (71.8m points)

jquery - scrolltop with animate not working

I'm trying to animate while scrolling but no luck with my code...

I have this jquery

$(window).scrollTop(200);

Now wanted to give animation effect

So tried these but not working:

1. $(window).animate({scrollTop:200},1000);
2. $('body').animate({scrollTop: 200}, 1000);

I have applied this in a click function like this:

$('.goto').click(function(){
    $(window).scrollTop(485); // its working
});

And now I want to give effect of animate but not working...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have to use $('html,body') instead of $(window) because window does not have a scrollTop property.

$('#scroll-bottom').on('click', function() {
  $('html, body').animate({
    scrollTop: 2000
  }, 2000); // for all browsers
  
  // $('html').animate({scrollTop: 2000}, 2000); // works in Firefox and Chrome
  // $('body').animate({scrollTop: 2000}, 2000); // works in Safari
})
#top {
  margin-bottom: 2000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="top">
  <button id="scroll-bottom">scroll</button>
</div>
<div>bottom</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...