如何禁用輸入按按鈕?禁用輸入按鍵輸入按鈕
我正在製作遊戲,你按下一個按鈕,然後一個計數器計數你按下並顯示文本,問題是當你按下回車鍵時計數器快速上升...這裏是遊戲:「 http://gorillapps.net/games/Button-Clicker.html「。
那麼如何禁用JavaScript中默認的按鍵?
如何禁用輸入按按鈕?禁用輸入按鍵輸入按鈕
我正在製作遊戲,你按下一個按鈕,然後一個計數器計數你按下並顯示文本,問題是當你按下回車鍵時計數器快速上升...這裏是遊戲:「 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.
}
}
這可以防止通過輸入執行按鈕。
高級解決方案。回車只允許一次。用戶必須放開輸入按鈕才能重置。
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
,然而,這是這樣一個簡單的網站,目的只有一個,內聯的事件在這裏是沒有問題的。
請提供一些代碼。 – Henrik 2015-02-09 14:06:47