我发现最简单的方法是“禁用”后退按钮点击。好的,从技术上讲,没有办法禁用它,但您可以让最终用户看到后退按钮已被禁用。我最初基于this blog post 开发了我的代码。这是一本很好的读物,因为他详细解释了这种方法。从那时起,我已经改进了他的代码,详细如下。
所以我这样定义preventBackButton ()。
function preventBackButton () {
// Triggered when the back button is pressed, it will detect if the url hash changes from #rms to #no-back. If it does, then
// it harmlessly changes the url hash forward again by going from "#no-back" to "#rms".
// On initial page load, pushes states "#no-back" and "#rms" onto the history, making it the most recent "page" to detect future "back" button presses.
var history_api = typeof history.pushState !== 'undefined';
if ( history_api ) {
history.pushState(null, '', '#no-back');
history.pushState(null, '', '#rms');
} else {
location.hash = '#no-back';
location.hash = '#rms';
}
// This function creates an event handler on hash changes. This is coded to detect back button clicks.
window.onhashchange = function() {
// location.hash becomes "#no-back" when the user clicks back button
if ( location.hash === '#no-back' ) {
if ( history_api ) {
history.pushState(null, '', '#rms');
} else {
location.hash = '#rms';
}
}
};
} // function preventBackButton ()
然后我打电话给$(document).ready()
$(document).ready(function() {
preventBackButton();
// Do other stuff...
});