在HTML表单上失去焦点时,如何重新聚焦到文本字段? [英] How to re-focus to a text field when focus is lost on a HTML form?

查看:233
本文介绍了在HTML表单上失去焦点时,如何重新聚焦到文本字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HTML表单上只有一个文本字段.用户输入一些文本,按Enter键,提交表单,然后重新加载表单.主要用途是条形码读取.我使用以下代码将焦点设置为文本字段:

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).

但是,当用户在浏览器窗口中的字段之外(空白区域)单击某个位置时,光标消失了.一个单一字段的HTML表单,如何防止光标丢失?或者,丢失光标后如何将光标重新聚焦在字段内?谢谢!

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!

推荐答案

Darin的回答是正确的,但在Firefox中不起作用.如果您也想在Firefox中重新获得焦点,则必须将其延迟到事件发生后:

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

或者更好的是,从JavaScript中分配:

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>

但是,我强烈建议您不要这样做.在文本框外单击以从该文本框移出焦点是完全正常的浏览器行为,这可能是合法使用的行为(例如,为ctrl-F设置搜索点或开始拖动选择等).不太可能有充分的理由来破坏这种预期的行为.

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.

这篇关于在HTML表单上失去焦点时,如何重新聚焦到文本字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆