0

我得到了这个脚本...

$(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 <--注意哈希。

提前致谢!

4

1 回答 1

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/

于 2012-10-09T06:51:25.287 回答