hashchange函数的例外 - 浏览器历史记录回来了吗?

时间:2012-01-03 17:03:18

标签: javascript jquery hash hashchange

我不知道我怎么称呼这个问题......这个问题的标题根本没有任何意义,我知道!

以下案例:我有一个单页面布局,用户向下滚动。我有部分.layer,当在视口内部时,应将地址栏中的哈希值更改为id。所以例如.layer#one位于视口内,地址栏中的网址如下所示:www.whatever.com /#!/ one

$(window).scroll(function() {       
    hash = $('.layer:in-viewport').attr('id');
    top.location.hash = "!/" + hash;
});

这很好用,就像我想要的那样。我使用!/语法的原因是,如果我只是将位置设置为hash,则只有滚动行为才会出错,因为浏览器会尝试坚持哈希位置。

现在的问题是,我希望能够使浏览器历史记录返回按钮正常工作! 使用jQuery附带的hashchange函数通常会非常简单......

$(window).bind( 'hashchange', function( event ) {
    //query the hash in the addressbar and jump to its position on the site
});

我遇到的唯一问题是,如果在滚动时更改了哈希,也会触发哈希交换功能。所以它会再次跳转或坚持浏览器中的当前位置。知道怎么解决这个问题吗?我可以在滚动时取消绑定hashchange,对吧?但这是最好的解决方案吗?

1 个答案:

答案 0 :(得分:2)

当然,只要滚动时哈希值发生变化,你就可以解除绑定并重新绑定。例如:

var old_hash;

var scroller = function() {       
    hash = $('.layer:in-viewport').attr('id');

    if ( old_hash != hash ) {
      $(window).off('hashchange', GoToHash); // using jQuery 1.7+ - change to unbind for < 1.7
      top.location.hash = "!/" + hash;

      setTimeout(function() { // ensures this happens in the next event loop
        $(window).on('hashchange', GoToHash);
      }, 0);

      old_hash = hash;
    }
}

var GoToHash = function() {
  //query the hash in the addressbar and jump to its position on the site
}

$(window).scroll(scroller);