问题
I'm having troubles trying scroll automatically with javascript. My scrolling area is the body, my js code is
$("body").animate({scrollTop: $("#myDiv").position().top)
but I don't get any result: no animation and no scrolling I also tried
$("body").scrollTop($("#myDiv").position().top);
and also replacing
$("body") with $(window).
Any hint?
回答1:
scrollTop
is a jQuery method which gets or sets the the offset of the current elements scroll bar, but with no animation.
You might be getting confused with the jQuery plugin scrollTo, which offers the functionality you're after.
You'd use it like;
$(window).scrollTo($('#myDiv');
回答2:
scrollTop
is a javascript attribute and you can use it like :
document.body.scrollTop = scrollValue;
or
$("body").get(0).scrollTop = scrollValue;
and there's a plugin named jQuery ScrollTo written by Ariel Flesler if you want to animate the scrolling:
http://demos.flesler.com/jquery/scrollTo/
回答3:
Try following code,
$('html,body').animate({scrollTop: $("#myDiv").offset().top},500);
回答4:
Note: if you have chrome://flags/#enable-experimental-web-platform-features enabled, the plugin listed above won't work. It's a known issue: https://github.com/flesler/jquery.scrollTo/issues/92
来源:https://stackoverflow.com/questions/10450471/jquery-scrolltop-doesnt-scroll