<div id="top" name="top" style="height:3000px;"></div>
<a href="#top">回顶部</a>
方法一
$('a').click(function(){
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
return false;
});
延伸
$(document).on('click', 'a', function(event){
event.preventDefault();
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
});
方法二
$('a').click(function(){
$(document).animate({
scrollTop:$(this.hash).offset().top
},500)
return false;
})
如果你的目标元素没有ID,也可以用设置name来链接:
$('a').click(function(){
$('html, body').animate({
scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top
}, 500);
return false;
});
为了提高性能,应该缓存该$(‘html,body’)选择器,以便每次单击锚点时都不会运行:
var $root = $('html, body');
$('a').click(function() {
$root.animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
return false;
});
如果要更新链接地址URL,在animate回调中执行即可
var $root = $('html, body');
$('a').click(function() {
var href = $.attr(this, 'href');
$root.animate({
scrollTop: $(href).offset().top
}, 500, function () {
window.location.hash = href;
});
return false;
});