试图将焦点设置在隐藏的文本框中

jac*_*row 9 jquery

我试图将焦点放在隐藏的文本框上.我希望当包含文本框的主体或div加载焦点时,应该在特定文本框上,以便键盘或任何其他设备的任何输入都被此元素捕获.我试过以下代码没有效果:

<body>
    <input type="text" id="exp" maxlength="16"></input>
    <input type="text" id="exp2" maxlength="16"></input>
    <script>
        $("#exp").hide();
        $("#exp").focus();
        $("#exp2").keypress(function(){
            alert($("#exp").val());
        });
    </script>
</body>
Run Code Online (Sandbox Code Playgroud)

提出任何建议.jquery解决方案将是首选.

Nat*_*all 12

您无法将焦点设置为通过该hide方法隐藏的文本框.相反,您需要将其移出屏幕.

<body>
<!-- it's better to close inputs this way for the sake of older browsers -->
<input type="text" id="exp" maxlength="16" />
<input type="text" id="exp2" maxlength="16" />
<script>
// Move the text box off screen
$("#exp").css({
    position: 'absolute',
    top: '-100px'
});
$("#exp").focus();
$("#exp2").keypress(function(){
alert($("#exp").val());
});
</script>
</body>
Run Code Online (Sandbox Code Playgroud)

  • ;-)信不信由你,这是一个非常标准的解决方案.干杯! (3认同)