您所做的就是获取要滚动到的元素的垂直偏移量,然后为该元素(或您正在滚动的任何元素)的scrollTop属性设置动画:window
//bind to all links whose `href` attribute starts with a hash
$('a[href^="#"]').on('click', function () {
//get the offset from the document's top for the element targeted in the links `href` attribute
var offset = $($(this).attr('href')).offset().top;
//scroll the document, some browsers use `html`, some use `body`
$('html, body').stop().animate({ scrollTop : offset }, 1000);
});
这是一个演示:http: //jsfiddle.net/wCgA7/1/
请注意,如果您提供导航position:fixed,您可以将其停靠在视口的顶部。