How to scroll to a part of the page using jQuery?
My code scrolls the user to the bottom of the page:
var $elem = $('body');
$('html, body').animate({scrollTop: $elem.height()}, 800);
How can it be modified to take the user to the p开发者_开发问答art of the page where there is a h3 tag with the id "myTitle":
<h3 id="myTitle">Hello</h3>
How about:
var $elem = $("#myTitle");
$('html, body').animate({scrollTop: $elem.offset().top}, 800);
using .offset()
.
Here's a working example: http://jsfiddle.net/naTjL/
You can get the offset of the element from the top:
var position = $("#myTitle").offset().top;
You can then use that as the value to scroll to.
This is a brilliant example
That even works with JS turned off. Additionally this adds the #myTitle
to the URL allowing bookmarking.
$('html, body').scrollTop($("#myTitle").offset().top)
精彩评论