javascript 如何在jquery中检测F5刷新按键事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13872853/
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
how to detect an F5 refresh keypress event in jquery?
提问by chaonextdoor
I noticed that jquery has a keypress function. But it seems that it can only detect keypress event of numbers and characters. It cannot detect the F5 keypress event. And What surprises me the most is everyone online says that the keyCode of F5 is 116, But when I use the jquery keypress function, it just shows that the character t has the keyCode of 116(it seems that 116 is the ascii code of lowercase t)! Can somebody give me any idea about this and how to detect the F5 event in javascript or jquery? Thanks so much in advance.
我注意到 jquery 有一个按键功能。但它似乎只能检测数字和字符的按键事件。它无法检测到 F5 按键事件。而最让我吃惊的是网上大家都说F5的keyCode是116,但是我用jquery的keypress函数时,却只显示字符t的keyCode是116(貌似116是小写的ascii码吨)!有人可以给我任何想法以及如何在 javascript 或 jquery 中检测 F5 事件吗?非常感谢。
回答by u283863
I don't know what you did wrong in your code, but jQuery does say F5
is 116
and t
is 84
:
我不知道你在代码中做错了什么,但 jQuery 确实说F5
是116
和t
是84
:
One possible error is keypress
will have different keycode
, that's why keydown
is more preferred.
一个可能的错误是keypress
会有不同的keycode
,这就是为什么keydown
更受欢迎。
| T | A | F5
keydown | 86 | 65 | 116
keypress| 116 | 97 | -
Also pressing F5
will not trigger keypress
because the reload part happens before keypress
.
同样按下F5
不会触发,keypress
因为重新加载部分发生在 之前keypress
。
回答by Ricky Jiao
The keypress event does not accept function keys(F1-F12). You can try to use keydown event.
按键事件不接受功能键(F1-F12)。您可以尝试使用 keydown 事件。
回答by reza akhlaghi
this code works good for me
i tested it in chrome and firefox successfully
这段代码对我很有用,我
在 chrome 和 firefox 中成功测试了它
<script>
document.onkeydown = capturekey;
document.onkeypress = capturekey;
document.onkeyup = capturekey;
function capturekey(e) {
e = e || window.event;
//debugger
if (e.code == 'F5') {
if (confirm('do u wanna to refresh??')) {
//allow to refresh
}
else {
//avoid from refresh
e.preventDefault()
e.stopPropagation()
}
}
}
</script>