更改自动滚动的 URL(推送状态?

Change URL for autoscroll (pushstate?)

本文关键字:状态 URL 滚动      更新时间:2023-09-26

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

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

非常感谢!!

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

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