这不是讲究用户体验嘛,所以点击那些“返回顶部”,或者页面内定位锚链接的时候能够平滑滚动页面自然让人比较舒服。下面这个代码记录一下,备用。
注:jQuery代码,需要jQuery库才能运行
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | $(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) { var targetOffset = $target.offset().top; $('html,body').animate({scrollTop: targetOffset}, 1000); return false; } } }); }); |
加了此段代码之后就能实现平滑滚动了。当然,如果需要像淘宝商品页面那样,在顶部的时候隐藏链接,拉下去的时候就出来的话,可以自行对此代码进行改造。

