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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:01:15  来源:igfitidea点击:

how to detect an F5 refresh keypress event in jquery?

javascriptjquerykeypress

提问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 F5is 116and tis 84:

我不知道你在代码中做错了什么,但 jQuery 确实说F5116t84

http://jsfiddle.net/Brjb2/1

http://jsfiddle.net/Brjb2/1

One possible error is keypresswill have different keycode, that's why keydownis more preferred.

一个可能的错误是keypress会有不同的keycode,这就是为什么keydown更受欢迎。

        |  T  |  A  |  F5
keydown |  86 |  65 | 116
keypress| 116 |  97 |  -

Also pressing F5will not trigger keypressbecause 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>