How can I scroll to the div automatically when I click the button?
I Have a button at the top, 4 tables in the middle and a div (id="Master开发者_如何学JAVADiv") on the bottom of a page. How can I scroll to the div automatically when I click the button? Thanks
You can use this function (which uses jQuery's .animate
)
function scrollToElement(selector, callback){
var animation = {scrollTop: $(selector).offset().top};
$('html,body').animate(animation, 'slow', 'swing', function() {
if (typeof callback == 'function') {
callback();
}
callback = null;
});
}
You call it like this:
scrollToElement('#MasterDiv');
Or if you want to include a callback:
scrollToElement('#MasterDiv', function(){
alert('Page scrolled');
});
Example
A named anchor inside an HTML document:
<a name="tips">Useful Tips Section</a>
Create a link to the "Useful Tips Section" inside the same document:
<a href="#tips">Visit the Useful Tips Section</a>
Or, create a link to the "Useful Tips Section" from another page:
<a href="http://www.w3schools.com/html_links.htm#tips">
Visit the Useful Tips Section</a>
source
You could try this library: http://demos.flesler.com/jquery/scrollTo/
No animation basic Javascript Example (use ID instead of the name attribute)
window.location = "#MasterDiv";
More on window.location
Jquery Animation Example
$.scrollTo("#MasterDiv");
ScrollTo Jquery Plugin
精彩评论