jquery 使用 keydown 专注于输入

jquery focus on an input using keydown

如果一个输入没有聚焦,如何通过按下回车键来聚焦它。(没有按钮或任何其他涉及。只有一个输入。)

例如:

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

编辑: 采用 ehsan 的方法,稍作修改:

if(e.which == 13 && $(document.activeElement).not("#user-input")) {
    $("#user-input").focus();
}
$(window).keydown(function(e) {
    if(e.keyCode == 13) {
        $("#input").focus();
    }
});

您可以为 <textarea> 禁用此功能:

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

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();

    }

  });



});

试试这个:

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>