javascript 如何防止元素失去焦点?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16038912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 03:01:06  来源:igfitidea点击:

How to prevent an element from losing focus?

javascriptjquery

提问by C_Major

How to keep the Focus on one textbox ? even if you click anywhere in a browser.

如何将焦点保持在一个文本框上?即使您单击浏览器中的任意位置。

$("#txtSearch").focus();

回答by Konstantin Dinev

You need to subscribe to the blurevent of the textboxand reinstate focus with a small timeout:

您需要订阅blur事件textbox并在一个小的超时时间内恢复焦点:

$('#txtSearch').blur(function (event) {
    setTimeout(function () { $("#txtSearch").focus(); }, 20);
});

This way you don't rely on subscribing to the events of any other element on the page. If you subscribe to body clickor html click, it won't run if any other element prevents propagation of its clickevent, also it won't work when tabbing out of the textbox.

这样您就不必依赖于订阅页面上任何其他元素的事件。如果您订阅body clickhtml click,如果任何其他元素阻止其click事件的传播,它将不会运行,也不会在跳出textbox.

Example:

例子:

<!-- 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>

回答by Curt

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

Live Demo:http://jsfiddle.net/QhaLY/

现场演示:http : //jsfiddle.net/QhaLY/

回答by user1032531

$('body').click(function(){$("#txtSearch").focus();});

回答by Alan Bogu

There are other ways of loosing focus than clicking area away from the input i.e. tabbing. If you want to prevent loosing focus use blur event i.e.

除了单击远离输入的区域(即 Tab 键)之外,还有其他失去焦点的方法。如果你想防止失去焦点使用模糊事件即

document.getElementById('txtSearch').addEventListener('blur', e => {
  e.target.focus();
});

回答by hamboy75

Konstantin Dinev answer works ok in must cases, but if you dont want to lose the focus only when clicking on certain parts of the html just do this:

Konstantin Dinev 的答案在必须的情况下可以正常工作,但是如果您不想仅在单击 html 的某些部分时才失去焦点,请执行以下操作:

$(".nofocus").on( "mousedown", function (e) {
    return false;
});

In my case i'm doing a small html text editor and i dont want to lose the control when pressing an action button but yes in any other case.

就我而言,我正在做一个小的 html 文本编辑器,我不想在按下操作按钮时失去控制权,但在任何其他情况下都是如此。

I just need to add the nofocus class to the button and it will not take the control

我只需要在按钮上添加 nofocus 类,它就不会控制

回答by David Eichelsd?rfer

It's also possible without jQuery and without re-focusing, if you just need a click on specific elements to not grab the focus

如果您只需要单击特定元素来不获取焦点,则无需 jQuery 且无需重新聚焦也是可能的

just listen for the mousedown event and cancel it

只需监听 mousedown 事件并取消它

element.addEventListener("mousedown", event => {event.preventDefault(); event.stopPropagation()});