jQuery平滑滚动和URL字段

时间:2012-03-17 18:21:48

标签: jquery url scroll append smooth-scrolling

我有这个脚本......

$(function(){
$('a[href*=#]:not([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) {
            $('html,body').animate({ scrollTop: target.offset().top }, 1000);
            location.hash = (this.hash);
            return false;
        }
    }
});
});

...但是我在页面滚动时跳到顶部有一个问题,但是如果我把它拿出来......

location.hash = (this.hash);

它可以正常工作并且滚动都很好,但URL不会附加到被点击的锚链接。

基本上我需要显示的网址:http://www.example.com/#home< - 请注意哈希。

提前致谢!

1 个答案:

答案 0 :(得分:0)

使用.animate

的回调
$(function(){
$('a[href*=#]:not([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 hash = this.hash; // 'this' will not be in scope in callback
            $('html,body').animate({ scrollTop: target.offset().top }, 1000, function() {
                location.hash = hash;
            });
            return false;
        }
    }
});
});

http://api.jquery.com/animate/