JQuery 实现锚点链接之间的平滑滚动
1、载入 JQuery 库,这个不用多说了吧,是前提,是必须,个人推荐 JQuery 1.2系列的版本。
2、关键代码:
$(document).ready(function() {
$('a[href*=#]').click(function() {
if(location.pathname.replace(/^\//,'') ==this.pathname.replace(/^\//,'') &&location.hostname==this.hostname) {
var$target=$(this.hash);
$target=$target.length&&$target|| $('[name='+this.hash.slice(1) +']');
if($target.length) {
vartargetOffset=$target.offset().top;
$('html,body').animate({
scrollTop:targetOffset
},
1000);
returnfalse;
}
}
});
});
$('a[href*=#]').click(function() {
if(location.pathname.replace(/^\//,'') ==this.pathname.replace(/^\//,'') &&location.hostname==this.hostname) {
var$target=$(this.hash);
$target=$target.length&&$target|| $('[name='+this.hash.slice(1) +']');
if($target.length) {
vartargetOffset=$target.offset().top;
$('html,body').animate({
scrollTop:targetOffset
},
1000);
returnfalse;
}
}
});
});