问题
I have a click that changes things on the page when you click it. I was wondering if there was a way to trigger an effect when you press the back button on the browser
回答1:
You can sort of do it using the popstate event:
window.onpopstate = function() {
alert("pop!");
}
or in jQuery:
$(window).on('popstate', function(event) {
alert("pop");
});
However this will also trigger when navigating forward, not only backward.
回答2:
Disable back url
$(function() {
if (window.history && window.history.pushState) {
window.history.pushState('', null, './');
$(window).on('popstate', function() {
// alert('Back button was pressed.');
document.location.href = '#';
});
}
});
回答3:
You can simply fire the “popState” event in JQuery e.g:
$(window).on('popstate', function(event) {
alert("pop");
});
This is enough for what you asked … but here are few add on window event to go with…
$(window).on('pushstate', function(event) {
alert("push");
}); // This one pushes u to forward page through history...
window.history.replaceState(); //work exactly like pushstate bt this one replace the history instead of creating new one...
window.history.backward(); // To move backward through history, just fire this event...
window.history.forward();// To move forward through history ...
window.history.go(-1); // Go back to one page(or whatever value u passed) through history
window.history.go(1); // Go forward to one page through history..
来源:https://stackoverflow.com/questions/17628612/jquery-when-back-button-is-pressed