试图抑制退格键和F5键同时也抑制了小写字母"按钮

Trying to suppress the backspace and F5 button is also suppressing the lower case "t" button

本文关键字:小写字 quot 按钮 F5      更新时间:2023-09-26

我试图阻止用户在输入一些文本时离开页面。我是通过按下F5键和退格键来做到这一点的。

现在我注意到我不能按t。当我检查日志时,这是因为t给了我一个116的键事件代码,与F5按钮相同。

我怎样才能绕过这个?

下面是一个代码片段:

function suppressBackspaceAndF5(evt) {
    evt = evt || window.event;
    var target = evt.target || evt.srcElement;
    // when I release "t" - the code is 116, which is the same as the refresh code.
    console.log(evt.keyCode);
    if ((evt.keyCode == 8 && 
         !/input|textarea/i.test(target.nodeName)) || 
         evt.keyCode == 116) {
            return false;
    }
}
document.onkeydown = suppressBackspaceAndF5;
document.onkeypress = suppressBackspaceAndF5;
<input></input>

我发现这个相关的Stackoverflow问题似乎包含了你的答案。专门在这里发布作为参考:

在javascript中使用window.event. keycode捕获f5按键事件。Onbeforeunload事件总是0而不是116

节选自SO用户Sim_ba

不要用e.keyCode == 166,用e.code == 'F5'代替。

function fkey(e){
e = e || window.event;
if( wasPressed ) return; 
function fkey(e){
    e = e || window.event;
    if (e.code === 'F5') {
        alert("f5 pressed");
        wasPressed = true;
    }else {
        alert("Window closed");
    }
}

这是因为't'和'F5'都使用了键码116。[…]

也去给Sim_ba投票吧!:)