文章内容
本文介绍jQuery锚点点击实现平滑滚动功能
关键代码
<script>
//定义页面所有锚点点击平滑滚动
$(function () {
$('a[href*=#],area[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) {
var targetOffset = $target.offset().top;
$('html,body').animate({
scrollTop: targetOffset
},
1000);
return false;
}
}
});
})
//定义页面某元素下的所有锚点点击平滑滚动
$(function () {
$('.maodian a[href*=#]').click(function () {
$(this).addClass('cur').siblings().removeClass('cur');
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) {
var targetOffset = $target.offset().top;
$('html,body').animate({
scrollTop: targetOffset
},
1000);
return false;
}
}
});
})
</script>
