簡體   English   中英

禁用 Enter 鍵單擊按鈕

[英]Disable enter key to click a button

你怎么能禁用輸入鍵來點擊一個按鈕。 所以當一個按鈕被聚焦時,按下回車鍵你不會點擊按鈕。


我制作了一個 Aim Trainer 代碼,但有一個秘訣:您可以按 Enter 按鈕進行點擊,而不是用鼠標(或移動設備上的手指)點擊。

你可以在這里看到我的意思https://aimtrainer.netlify.com/clickbased.html

如果您點擊回車按鈕,應該什么也不會發生,但是現在您將觸發某種點擊事件。

我試過這個:但這行不通

$('html').bind('keypress', function(e){
  if(e.keyCode == 13)
  {
    return false;
  }
});

你試過e.preventDefault()嗎?

$(document).on('keypress',function(e) {
    if(e.which == 13) {
        e.preventDefault()
    }
});

你需要 preventDefault() 和 blur

其他好主意: tabindex="-1" type="button"

 let score = 0; const addScore = function(val) { score += val; $("#score").html('score: ' + score); } const newRandomPosition = function() { $("#button").css({ 'left': ranNum(90) + 'vw', 'top': ranNum(90) + 'vh', 'opacity': 1 }) } const ranNum = function(max) { return Math.random() * max } $(function() { $(document).on('keypress', function(e) { if (e.target && e.target.id === "button" && e.which == 13) { e.preventDefault() } }); $("#button") .on("click", function(e) { e.preventDefault(); // openFullscreen() $(this).css("opacity", 0) addScore(100) newRandomPosition() }) .on("focus", function() { this.blur() }) });
 .button { position: relative; background-color: #FB6107; border: none; color: white; padding: 20px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button tabindex="-1" type="button" id="button" class="button button5"></button> <h1 id="score" class="scoreText">Score: 0</h1>

tabindex設置為 -1 以避免使用Tab鍵聚焦

<button id="button" class="button button5" onclick="hidebtn(this)" tabindex="-1"></button>

使用blur()手動聚焦按鈕

function newRandomPostion(){
    $("#button").css({left:ranNum(90)+'vw',top:ranNum(90)+'vh'});
    $("#button").css('opacity', 1);
    $("#button").blur();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM