How to re-focus to a text field when focus is lost on a HTML form?

▼魔方 西西 提交于 2019-12-01 03:58:37

问题


There is only one text field on a HTML form. Users input some text, press Enter, submit the form, and the form is reloaded. The main use is barcode reading. I use the following code to set the focus to the text field:

<script language="javascript">
    <!--
            document.getElementById("#{id}").focus()
    //-->
</script>

It works most of the time (if nobody touches the screen/mouse/keyboard).

However, when the user click somewhere outside the field within the browser window (the white empty space), the cursor is gone. One a single field HTML form, how can I prevent the cursor from getting lost? Or, how to re-focus the cursor inside the field after the cursor is lost? thx!


回答1:


Darin's answer is right, but doesn't work in Firefox. If you want to steal focus back in Firefox too, you have to delay it until after the event:

<input onblur="var that= this; setTimeout(function() { that.focus(); }, 0);">

Or, better, assigned from JavaScript:

<script type="text/javascript">
    var element= document.getElementById('foo');
    element.focus();
    element.onblur= function() {
        setTimeout(function() {
            element.focus();
        }, 0);
    };
</script>

But, I would strongly advise you not to do this. Clicking outside a text box to remove focus from that text box is perfectly normal browser behaviour, which can be of legitimate use (eg. to set search point for ctrl-F, or start a drag-selection, etc). There's very unlikely to be a good reason to mess with this expected behaviour.




回答2:


<input type="text" name="barcode" onblur="this.focus();" />



回答3:


You can hook the blur event and refocus the field again. There are very few use cases for doing this, but it sounds like yours may be one of them. Note that you'll probably have to schedule the re-focus via setTimeout or similar, you won't be able to do it within the blur handler itself.

When doing this without affecting the markup, this is easiest if you use a library like Prototype, jQuery, Closure, etc., but you can do it without them (of course), you just have to handle browser differences yourself. For instance, using Prototype:

document.observe("dom:loaded", function() {
    var elm = $('thingy');

    elm.focus();
    elm.observe('blur', function() {
        refocus.defer(elm);
    });

    function refocus(elm) {
        elm.focus();
    }
});

If you don't mind affecting the markup, you can use the onblur attribute. For instance, this works on IE, Firefox, and Chrome at least (probably others):

HTML:

<input type='text' id='thingy' onblur="refocus(this);">

Script:

function refocus(elm) {

    setTimeout(go, 0);

    function go() {
        elm.focus();
    }
}


来源:https://stackoverflow.com/questions/2605974/how-to-re-focus-to-a-text-field-when-focus-is-lost-on-a-html-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!