我什至不知道我应该怎么称呼这个问题……这个问题的标题根本没有任何意义,我知道!
以下案例:我有一个单页布局,用户可以向下滚动。我有 .layer
部分,当在视口(viewport)内时,应该将地址栏中的散列更改为它的 id
。所以例如.layer#one
在视口(viewport)内地址栏中的 url 看起来像这样 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
});
我遇到的唯一问题是,如果在滚动时哈希值发生变化,哈希值更改函数也会被触发。所以它会再次跳转或停留在浏览器中的当前位置。知道我该如何解决这个问题吗?我可能可以在滚动时取消绑定(bind) hashchange,对吧?但这是最好的解决方案吗?
最佳答案
当然,只要哈希值在滚动时发生变化,您就可以解除绑定(bind)并重新绑定(bind)。例如:
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);
关于javascript - hashchange 函数的异常 - 浏览器历史记录回来了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8715829/