Javascript:退出键 = 浏览器后退按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6390417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript: Escape key = browser back button
提问by Ryan
In a browser how can I make the keyboard's escape key go back in Javascript.
在浏览器中,如何让键盘的转义键在 Javascript 中返回。
For example: if you visit this pageand 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?
使这种魔法发生的 Javascript 是什么?
回答by Floern
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.
history.back()
如果按下 Escape 键(键码 27),这将调用。
回答by Avien
$(document).bind("keyup", null, function(event) {
if (event.keyCode == 27) { //handle escape key
//method to go back }
});
回答by basicxman
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.
您可以将onkeyup
事件处理程序绑定到window
并检查键码是否为27
(用于 Escape的键码),然后使用该window.history.back()
函数。
window.onkeyup = function(e) {
if (e.keyCode == 27) window.history.back();
}
MDC docs on window.history
, https://developer.mozilla.org/en/DOM/window.history
MDC 文档window.history
,https://developer.mozilla.org/en/DOM/window.history
回答by Daniel A. White
Just listen for key code 27 and call history.go(-1);
只需听键代码 27 并调用 history.go(-1);
回答by Igor
You need to listen for the 'ESC' keypress, and fire off the back action when it is pressed, like so:
您需要监听 'ESC' 按键,并在按下时触发 back 动作,如下所示:
document.onkeydown = function(e){
if (window.event.keyCode == 27) {
history.go(-1);
}
};