2012-01-03 136 views
1

我不知道我该怎么称呼这个问题......这个问题的标题根本没有任何意义,我知道!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功能也将被触发。所以它会再次跳转或坚持到浏览器中的当前位置。任何想法我怎么能解决这个问题?我可以在滚动的时候解开hashchange,对吧?但这是最好的解决方案吗?

回答

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); 
+0

嗯,谢谢你的这种做法。看起来非常好,但我似乎无法使它工作。我将我的代码发布到jsfiddle,但演示当然不适用于jsfiddle网站。 http://jsfiddle.net/JDpqs/ – matt 2012-01-04 21:33:31

+0

你是否包含这个来获取:in-viewport? http://goo.gl/apfUa – glortho 2012-01-05 02:22:21

+0

顺便说一句,如果你可以负担得起使用pushState/onpopstate,它会很好。 – glortho 2012-01-05 02:38:04