我们将通过点击<a>标签跳转到 id为content的指定位置那里。
<a id="turnToContent" href="#content"></a>
然后呢,就在我们想要的位置设置id为content的内容块,这里用一个div模拟一篇不像文章的文章。最好将此div放在靠后的位置,这样效果就很明显一点,如果只是测试一下这个效果,可以用简单粗暴的方法,在其前面放很多个<p>标签即可。
<div id="content">
<h2><a href="###">HTML5</a></h2>
<p>html5html5html5</p>
<p class="addMes">标签: <span>HTML5</span><small>2015年4月19日</small></p>
</div>
JQuery来实现平滑过渡的效果:
单个ID使用:
<script>
$('#turnToContent').click(function () {
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 500);
return false;
});
</script>
如果多处使用,为了写一堆ID,可以封装改进成以下函数:
<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;
}
}
});
})
</script>