定位锚平滑滚动jQuery代码

on Monday, February 22nd, 2010 at 3:42 pm by 阿辛

这不是讲究用户体验嘛,所以点击那些“返回顶部”,或者页面内定位锚链接的时候能够平滑滚动页面自然让人比较舒服。下面这个代码记录一下,备用。
注: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;
            }
        }
    });
});

加了此段代码之后就能实现平滑滚动了。当然,如果需要像淘宝商品页面那样,在顶部的时候隐藏链接,拉下去的时候就出来的话,可以自行对此代码进行改造。

日志所属分类: 2.Web程序开发 | 本文地址: http://xinple.org/?p=381
打印此文: Print This Post | TrackBack: http://xinple.org/wp-trackback.php?p=381

No Responses.

Leave a Reply

*