页面正常使用a标签链接到对应的元素
<div class="top">
<a href="#a1">1111</a>
<a href="#a2">2222</a>
<a href="#a3">3333</a>
<a href="#a4">4444</a>
</div>
<div class="content">
<div id="a1">1111</div>
<div id="a2">2222</div>
<div id="a3">3333</div>
<div id="a4">4444</div>
</div>
js中添加这个方法就可以了
$(function(){
//锚点跳转滑动效果
$('a[href*="#"],area[href*="#"]').click(function() {
console.log(this.pathname)
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 }, 200);
return false;
}
}
});
})