javascript - 更改自动滚动的 URL(pushstate?)

标签 javascript jquery pushstate

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

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

非常感谢!!!

最佳答案

运行它 when the animation is done :(nice demo here)

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

关于javascript - 更改自动滚动的 URL(pushstate?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11060186/

相关文章:

javascript - 在pushState上获取路径特定的cookie

javascript - Knockout动态更新observableArray值

javascript - jQuery 多次复制现有的 Div

jquery - 您可以使用 jQuery UI 自动完成组合框限制输入无效击键吗?

jquery - History.pushState 在浏览器后退按钮上中断

javascript - 为什么调用 History.pushState() (或 .replaceState())会触发 'popstate' 事件?

javascript - Marrionette ItemView onClose 方法何时被调用?

javascript - JS Regexp for letter that appears at least two twice in the string 任何地方

javascript - 元素悬停在 css3 淡入淡出效果中无法正常工作

javascript - 为什么盒子马上就消失了?