禁用回车键输入类型按钮

Disable enter key press in type button

本文关键字:类型 按钮 输入 回车      更新时间:2023-09-26

如何禁用回车按钮?

我正在制作一个游戏,你按下一个按钮,然后计数器计数你按下并显示文本,问题是当你按下回车键时,计数器会快速上升。。。游戏如下:"http://gorillapps.net/games/Button-Clicker.html".

那么,如何禁用Javascript中默认的按键呢?

document.getElementById("countButton").onkeydown = function(e){
if (e.which == 13) //13 is the keycode referring to enter.
    {
       e.preventDefault(); //this will prevent the intended purpose of the event. 
       return false; //return false on the event.
    }
}

这将阻止按enter键执行按钮。

高级解决方案。只允许输入一次。用户必须放开回车按钮才能重置。

var enterPressed = 0;
document.getElementById("countButton").onkeydown = function(e){
    if (e.which == 13)
        {
        if (!enterPressed)
        {
            enterPressed = 1;
            return true;
        }
        else
        {
            e.preventDefault();
            return false;
        }

    }
}
document.getElementById("countButton").onkeyup = function(e){
    if (e.keyCode == 13)
    {
        enterPressed = 0;
    }
}

通常我会提倡使用addEventListener,但这是一个简单的网站,只有一个目的,内联事件在这里不是问题。

您可以尝试以下代码:

$('#yourButtonId').keypress(function(event) {
    if (event.which == 13) {
        event.preventDefault();
    }
});

希望这会有所帮助。