0

我目前正在使用我发现的自动滚动到锚点的代码:

$(function() {
    $('nav a[href*=#]').bind('click',function(event){
        var $anchor = $(this);

        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top - 100
        }, 1000);
        event.preventDefault();

    });
});

我可以添加什么以确保在单击时将#anchor 添加到 URL 中?

我已经看到这个使用了,但我不知道如何添加它..

function() {
        if(history.pushState) {
            history.pushState(null, null, target);
        }
        else {
            location.hash = target;
        }
      });

非常感谢!!!

4

1 回答 1

2

动画完成后运行它:(这里很好的演示

$(function () {
    $('nav a[href*=#]').on('click', function (event) {
        var $anchor = $(this),
            name = $anchor.attr("href").match(/#(.+)/i)[1];

        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top - 100
        }, 1000, function () {
            if (history.pushState) {
                history.pushState(null, null, "#" + name);
            } else {
                location.hash = name;
            }
        });
        event.preventDefault();
    });
});

工作演示:http: //jsfiddle.net/DerekL/uPS9W/show

于 2012-06-16T02:19:23.000 回答