我已经设置了一个页面,在该页面中使用以下代码,当您单击链接时,内容和URL会更改而无需刷新:
window.history.pushState("object or string", "title", "/photo.php");
但是,当用户点击“返回”按钮时,内容不会改变回来。如何检测后退按钮?
我已经设置了一个页面,在该页面中使用以下代码,当您单击链接时,内容和URL会更改而无需刷新:
window.history.pushState("object or string", "title", "/photo.php");
但是,当用户点击“返回”按钮时,内容不会改变回来。如何检测后退按钮?
onpopstate
,即使在导航按钮被使用时也会触发它。
http://jsfiddle.net/54LfW/4/
window.onpopstate = function(e) { // executed when using the back button for example
alert("Current location: " + location.href); // location.href is current location
var data = e.state;
if(data) {
alert(JSON.stringify(e.state)); // additional data like your "object or string"
}
};
google.com/gmail#!/tempURL
。history.replaceState(null, document.title, location.pathname+"#!/tempURL");
2. 将上一个URL作为新状态推入,因此您的浏览器将显示上一个URL,即google.com/gmail
。
history.pushState(null, document.title, location.pathname);
堆栈的当前状态
第一个元素: google.com/gmail
最后一个元素: google.com/gmail#!/tempURL
3.现在添加监听器以监听事件
window.addEventListener("popstate", function() {
if(location.hash === "#!/tempURL") {
history.replaceState(null, document.title, location.pathname);
//replaces first element of last element of stack with google.com/gmail so can be used further
setTimeout(function(){
location.replace("http://www.yahoo.com/");
},0);
}
}, false);