Javascript 更改自动滚动的URL(pushstate?)

Javascript 更改自动滚动的URL(pushstate?),javascript,jquery,pushstate,Javascript,Jquery,Pushstate,我目前正在使用我找到的代码自动滚动到锚: $(function() { $('nav a[href*=#]').bind('click',function(event){ var $anchor = $(this); $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top - 100 }, 1000);

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

$(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();

    });
});
我可以添加什么来确保在单击时将#锚添加到URL

我见过这个,但我不知道如何添加它

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

运行它:()

工作演示:

$(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();
    });
});