2016-09-06 26 views
0

如果輸入聚焦輸入,如何只通過敲擊回車鍵重點關注一下。(世界上沒有其他按鈕或其他任何參與。只有一個輸入。)jQuery的重點放在使用的keydown

例如像:

$(!("input").focus().keydown(function(e){ 
    if(e.which == 13) { 
     $("#input").focus(); 
    } 
}); 

編輯: 去與伊赫桑的做法,略作修改:

if(e.which == 13 && $(document.activeElement).not("#user-input")) { 
    $("#user-input").focus(); 
} 
+0

也許,如果你沒有在你的代碼中的錯字。你應該正在聽按鍵的窗口 – epascarello

回答

1

試試這個:

HTML:

<input type="text" class="inputFocus"> 

jQuery的:

$(document).on("keypress",function(e){ 

    if(e.which==13 && !$(":focus").hasClass("inputFocus")) 
     $(".inputFocus").focus(); 

}) 

最終代碼:

<!DOCTYPE html> 
 
<html lang="en"> 
 
<head> 
 
    <meta charset="UTF-8"> 
 
</head> 
 
<body> 
 
    
 
    <input type="text" class="inputFocus"> 
 
    
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
 
    <script> 
 
    
 
    $(document).on("keypress",function(e){ 
 

 
     if(e.which==13 && !$(":focus").hasClass("inputFocus")) 
 
      $(".inputFocus").focus(); 
 

 
    }) 
 
    
 
     
 
    </script> 
 
    </body> 
 
</html>

0
$(window).keydown(function(e) { 
    if(e.keyCode == 13) { 
     $("#input").focus(); 
    } 
}); 

您可以<textarea>禁用此:

$("textarea").keydown(function (e) { 
    e.stopPropagation(); 
}); 
+0

他正在尋找一種解決方案,檢查輸入是否已經集中,你沒有檢查它「如果輸入未聚焦」 – Tomas

+0

ok將添加到代碼 –

+0

@Tomas I看到任何地方的OP說。 – epascarello

0

https://jsfiddle.net/moongod101/24m729nx/

let input = document.querySelector("input"); 
let idInput = document.querySelector("#input"); 

input.addEventListener("focus",function(){ 


    this.addEventListener("keydown",function(e){ 

    let keycode = e.keyCode; 
    if(keycode = 13){ 

     idInput.focus(); 

    } 

    }); 



});