How to go to a specific element on page?
This question already has an answer here:
The standard technique in plugin form would look something like this:
(function($) {
$.fn.goTo = function() {
$('html, body').animate({
scrollTop: $(this).offset().top + 'px'
}, 'fast');
return this; // for chaining...
}
})(jQuery);
Then you could just say $('#div_element2').goTo();
to scroll to <div id="div_element2">
. Options handling and configurability is left as an exercise for the reader.
If the element is currently not visible on the page, you can use the native scrollIntoView()
method.
$('#div_' + element_id)[0].scrollIntoView( true );
Where true
means align to the top of the page, and false
is align to bottom.
Otherwise, there's a scrollTo()
plugin for jQuery you can use.
Or maybe just get the top
position()
(docs) of the element, and set the scrollTop()
(docs) to that position:
var top = $('#div_' + element_id).position().top;
$(window).scrollTop( top );
document.getElementById("elementID").scrollIntoView();
Same thing, but wrapping it in a function:
function scrollIntoView(eleID) {
var e = document.getElementById(eleID);
if (!!e && e.scrollIntoView) {
e.scrollIntoView();
}
}
This even works in an IFrame on an iPhone.
Example of using getElementById: http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_document_getelementbyid
链接地址: http://www.djcxy.com/p/36594.html上一篇: HTML:如何创建“另存为”按钮?
下一篇: 如何去页面上的特定元素?