popstate - 需要点击两次返回按钮才能实际返回

6
我正在创建一个单页,并使用pushState更改地址。现在,如果我按回退键,popstate会被触发,我想要动画地滚动页面从当前位置到上一个位置。当然可以做到,但是页面会跳到顶部。
有人知道如何防止这种行为吗?我正在使用jQuery来动画滚动....
谢谢 :)
// 编辑:好的,我找到了,如果我动画滚动然后再更改URL,它就不会跳来跳去-但现在我必须双击返回按钮才能返回... http://www.testwebseiten.at/user/falk/stein-jagersbacher.at 代码有点混乱,所以我稍微解释一下:
    var scrollCurrentSection = function(event) {
        if (typeof event.preventDefault != 'undefined')
            event.preventDefault();

        var page = "";
        if (window.location.href.substr(-1) == '/')
            page = sjag.index;
        else
            page = window.location.href.match(/([^\/]+)$/)[1];

        $this       = $('a[href$="'+page+'"]');
        if ($this.length) {
            sjag.scrollToSection($this);
        }
    }
    window.onpopstate = scrollCurrentSection;

sjag包含多个选项和方法...因此sjag.index仅包含'index.php',sjag.scrollToSection包含动画。
单击导航链接时,将调用以下函数:
    // set navi
    $("#navi a, #navi-add a").click(function(event) {
        var data = $(this).data('sjagpage');
        if (typeof data == 'undefined')
            return;

        event.preventDefault();
        // animate scrolling
        $this   = $(this);
        sjag.scrollToSection($(this), function() {
            history.pushState("", "", $this.attr('href'));
        });
    });

$(this).data('sjagpage') 包含 jQuery 元素。

当我不使用动画滚动时,只需要单击即可返回 - 但是当我现在使用动画滚动时,需要两次...为什么?


我们需要代码。你能发一下吗? - Deepak Kumar
@Deepak:我已经完成了 - 希望你现在能更好地理解它 :) - lumio
1个回答

0
我认为问题在于event.preventDefault是由jQuery添加到event对象中的函数,但您没有使用jQuery绑定事件处理程序。因此,默认导航未被阻止,因此您最终会有两个历史记录项可供导航回去。
而不是:
window.onpopstate = scrollCurrentSection;

您应该像这样绑定它:

$(window).bind("popstate", scrollCurrentSection);

我看到了...动画或完成函数被调用了两次...我尝试隔离这个错误 :) 谢谢 - lumio
好的,问题在于我对html和body进行了动画处理 - 因此回调函数被执行了两次。 - lumio

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接