jquery专注于使用keydown的输入

时间:2016-09-06 16:50:22

标签: jquery input focus

如果输入没有聚焦,只需按下回车键即可专注于它。(没有按钮或其他任何涉及的东西。只有一个输入。)

例如:

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

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

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

3 个答案:

答案 0 :(得分:1)

试试这个:

<强> HTML

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

<强> jQuery的:

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

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

})

最终代码:

&#13;
&#13;
<!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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

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

您可以为<textarea>

禁用此功能
$("textarea").keydown(function (e) {
    e.stopPropagation();
});

答案 2 :(得分: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();

    }

  });



});
相关问题