简体   繁体   中英

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 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

只需听取密钥代码27并调用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);
   }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM