当 HTML 表单失去焦点时如何重新聚焦到文本字段?
HTML 表单上只有一个文本字段。用户输入一些文本,按 Enter 键,提交表单,然后重新加载表单。主要用途是条码读取。我使用以下代码将焦点设置到文本字段:
<script language="javascript">
<!--
document.getElementById("#{id}").focus()
//-->
</script>
它在大多数情况下都有效(如果没有人触摸屏幕/鼠标/键盘)。
但是,当用户单击浏览器窗口内字段之外的某个位置(白色空白区域)时,光标就会消失。一个单字段的HTML表单,如何防止光标丢失?或者,光标丢失后如何重新将光标聚焦在字段内?谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Darin 的答案是正确的,但在 Firefox 中不起作用。如果您也想在 Firefox 中夺回焦点,则必须将其推迟到事件发生之后:
或者更好的是,从 JavaScript 分配:
但是,我强烈建议您不要这样做。单击文本框外部以从该文本框移除焦点是完全正常的浏览器行为,可以合法使用(例如,为 ctrl-F 设置搜索点,或开始拖动选择等)。不太可能有充分的理由来扰乱这种预期的行为。
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:
Or, better, assigned from JavaScript:
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.
您可以挂钩
blur
事件并再次重新聚焦该字段。这样做的用例很少,但听起来你的可能就是其中之一。请注意,您可能必须通过setTimeout
或类似的方法安排重新聚焦,您将无法在blur
处理程序本身中执行此操作。在不影响标记的情况下执行此操作时,如果您使用像 Prototype、jQuery, 关闭等等,但你可以在没有它们的情况下做到这一点(当然),你只需要自己处理浏览器差异。例如,使用 Prototype:
如果您不介意影响标记,则可以使用
onblur
属性。例如,这至少适用于 IE、Firefox 和 Chrome(也可能是其他浏览器):HTML:
脚本:
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 viasetTimeout
or similar, you won't be able to do it within theblur
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:
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:
Script: