0

无论用户做什么,我都有一个始终需要关注的文本字段。

我通过这样做激活了加载时的文本字段:

<html>
<head>
    < script type ="text/javascript" src ="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></ script>
    < script type ="text/javascript">
    $( function () {
        $( "#myTextBox2" ).focus();
    });
    </ script>
</head>
< body>
    < div>
        < input type ="text" id ="myTextBox">
        < input type ="text" id ="myTextBox2"onblur="var that= this; setTimeout(function() { that.focus(); }, 0);">
    </ div>
</ body>
</html>

如果我在尝试上面的代码时按下选项卡按钮,我仍然可以远离 myTextBox2,但我无法用鼠标单击 myTextBox(这是正确的)。

如果用户按下任何按钮或单击站点上的任何位置,则仍应选择并聚焦文本字段。我如何完全执行此操作?

编辑:将此添加到我的代码中的标题和 Sven 的答案中似乎可以解决问题:

    $(document).keydown(function(objEvent) {
        if (objEvent.keyCode == 9) {  //tab pressed
            objEvent.preventDefault(); // stops its action
       }
    })

学分: 用 javascript 锁定 tab 键?

4

2 回答 2

4

You can keep the focus on the text field at all time with the following code:

HTML:

<form>
    <input type="text" name="name" id="focus" />
    <input type="text" name="name2" />
    <input type="text" name="name3" />
    <input type="text" name="name4" />
</form>

JS:

$(document).ready(function() {
    $("#focus").focus().bind('blur', function() {
        $(this).focus();            
    }); 

    $("html").click(function() {
        $("#focus").val($("#focus").val()).focus();
    });  

    //disable the tab key
    $(document).keydown(function(objEvent) {
        if (objEvent.keyCode == 9) {  //tab pressed
            objEvent.preventDefault(); // stops its action
       }
    })      
});​

Example on JsFiddle: Click!

I had to replace the value of the textfield to force/trigger the placement of the cursor in the focused field.

Hope this helps.

于 2012-12-20T10:23:36.537 回答
0

我会做到以下几点:

1)在页面加载时,使元素自动聚焦(已由您完成)

2) On #myTextBox2 create a key press event handler and discard every char except of the "real" input ones e.g. alfanumeric, dots, carets, and everything the user can actually input on that field

3) Create an onblur event handler on #myTextBox2 that actually focuses on the same input ( already done by you, I would suggest to put it on a script in the )

4) For completeness, put an Interval on your page that checks every X microseconds that the input is focused. If not, make the input focused. This is optional.

Be aware that, in any case, if a function call actually detects that the input is not focused, and has to focus it, the focus will be pointed at the beginning of the input, so the user input will re-begin from the beginning of the input field. The input contents will not be destroyed, however the user will have to jump to the end of the input after the re-focus.

If you need any help in creating the event handlers, just ask.

于 2012-12-20T10:20:51.193 回答