popstate - 需要点击两次后退按钮才能返回

问题描述:

我正在创建一个单页并使用pushState更改地址。现在,如果我推回来,popstate会被触发,并且想要将页面从当前位置滚动到最后位置。这当然有效,但页面跳转到顶部。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的元素。

当我没有设置动画滚动时,只需要一次点击就可以返回 - 但是当我现在为它设置动画时,它需要两个...为什么?

+0

我们需要的代码。你可以发布吗? – 2012-03-09 13:13:11

+0

@Deepak:我没有 - 我希望你现在了解一点:) – lumio 2012-03-09 13:38:58

我认为这个问题是event.preventDefault是添加到event对象的jQuery功能,但你不绑定使用jQuery的事件处理程序。因此,默认导航没有被阻止,因此最终有2个历史项目可以导航回去。

相反的:

window.onpopstate = scrollCurrentSection; 

你应该结合它像:

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

我看到了...动画或完成功能被调用两次...我试图隔离那个错误:)谢谢 – lumio 2012-03-09 14:07:07

+0

好的问题是我为html和body生成了动画 - 所以回调函数被执行了两次。 – lumio 2012-03-09 14:59:06