Javascript: Escape key = browser back button
In a browser how can I make the keyboard's escape key go back in Javascript.
For example: if you visit this page and click the "Fullscreen" link I'd like to press the 开发者_JAVA技巧escape key and go back to the previous page.
What's the Javascript to make this magic happen?
You can add a Key-Listener:
window.addEventListener("keyup", function(e){ if(e.keyCode == 27) history.back(); }, false);
This will call history.back()
if the Escape key (keycode 27) is pressed.
$(document).bind("keyup", null, function(event) {
if (event.keyCode == 27) { //handle escape key
//method to go back }
});
You can bind an onkeyup
event handler to window
and check if the keycode is 27
(keycode for Escape), then use the window.history.back()
function.
window.onkeyup = function(e) {
if (e.keyCode == 27) window.history.back();
}
MDC docs on window.history
, https://developer.mozilla.org/en/DOM/window.history
Just listen for key code 27 and call history.go(-1);
You need to listen for the 'ESC' keypress, and fire off the back action when it is pressed, like so:
document.onkeydown = function(e){
if (window.event.keyCode == 27) {
history.go(-1);
}
};
精彩评论