var currentHash,url; if (history && history.pushState) { $(window).scroll(function() { hash = $('.layer:in-viewport').attr('id'); catHash = $("#"+hash).parent('section').attr('id'); var data = "nothing"; if ( catHash != undefined ) url = "/" + catHash + "/" + hash; else url = "/" + hash; if ( currentHash != hash ) { window.history.pushState(data,hash,url); } currentHash = hash; }); }
现在我有两个问题:
1.)现在,当我滚动浏览页面时,地址栏中的URL会成功更改.我最初加载页面时如何查询地址栏中的url / hash.所以想象我现在有一个像www.url.com/deep这样的链接我想找出什么/深?我只需要查询整个top.location并将其拆分为每个“/”吗?我的意思是这些链接实际上不存在,那么在调用我使用pushState函数操作的url时如何避免使用404页面?
2.)如何在单击后退按钮时找到地址栏中的最后一次更改?所以我想在点击浏览器后退按钮时找到/深,这样我就可以回到页面上的那个位置.我想这可能与popstate有关,但我无法找到方法!
谢谢您的帮助!
更新:
window.history.pushState("test",url);
…
$(window).bind('popstate',function(event){ console.log(event.data); });
这总是空的.这不应该返回“测试”吗?
解决方法
what the first parameter in the pushState function is for?
state object — The state object is a JavaScript object which is associated with the new history entry created by pushState(). Whenever the user navigates to the new state,a popstate event is fired,and the state property of the event contains a copy of the history entry’s state object.
因此,当您返回该状态时,它会返回您选择的一组数据.
Right now the url in the addressbar changes successfully when I scroll through my page. How can I query the url/hash in the addressbar when I initially load the page.
查看位置对象…但您不需要.您可以(并且应该)填充页面服务器端.这是pushState的优势之一,如果JavaScript不可用并且服务器端回退顺利集成,则链接仍然有效.
How can I find out the last change in the addressbar when clicking the back button?
您添加一个事件侦听器(查找popState事件),并且您在其中存储的数据将在事件对象上可用. MDN has an example