简体   繁体   English

如何检测 jquery 中的 F5 刷新按键事件?

[英]how to detect an F5 refresh keypress event in jquery?

I noticed that jquery has a keypress function.我注意到 jquery 有一个按键功能。 But it seems that it can only detect keypress event of numbers and characters.但是好像只能检测数字和字符的按键事件。 It cannot detect the F5 keypress event.它无法检测 F5 按键事件。 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)?最让我吃惊的是网上大家都说F5的keyCode是116,但是我用jquery的keypress函数时,只显示字符t的keyCode是116(好像116是小写的ascii码吨)? Can somebody give me any idea about this and how to detect the F5 event in javascript or jquery.有人可以告诉我关于这个以及如何在 javascript 或 jquery 中检测 F5 事件的任何想法。 Thanks so much in advance.非常感谢。

I don't know what you did wrong in your code, but jQuery does say F5 is 116 and t is 84 :我不知道你在代码中做错了什么,但 jQuery 确实说F5116t84

http://jsfiddle.net/Brjb2/1 http://jsfiddle.net/Brjb2/1

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之前。

The keypress event does not accept function keys(F1-F12).按键事件不接受功能键(F1-F12)。 You can try to use keydown event.您可以尝试使用 keydown 事件。

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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