如何防止元素失去焦点? [英] How to prevent an element from losing focus?
本文介绍了如何防止元素失去焦点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使焦点集中在一个文本框上?即使您在浏览器中单击任意位置.
How to keep the Focus on one textbox ? even if you click anywhere in a browser.
$("#txtSearch").focus();
推荐答案
您需要订阅textbox
的blur
事件,并在较小的超时时间内恢复焦点:
You need to subscribe to the blur
event of the textbox
and reinstate focus with a small timeout:
$('#txtSearch').blur(function (event) {
setTimeout(function () { $("#txtSearch").focus(); }, 20);
});
通过这种方式,您不必依赖订阅页面上任何其他元素的事件.如果您预订body click
或html click
,则如果任何其他元素阻止其click
事件的传播,则它将不会运行,并且当跳出textbox
时,它也将不起作用.
This way you don't rely on subscribing to the events of any other element on the page. If you subscribe to body click
or html click
, it won't run if any other element prevents propagation of its click
event, also it won't work when tabbing out of the textbox
.
示例:
<!-- I will not propagate my click to top level DOM elements -->
<button id="button">Click me</button>
<script>
$('#button').click(function (event) {
event.stopPropagation();
});
</script>
这篇关于如何防止元素失去焦点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文