强制关注一个元素,但有例外。(jQuery)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3229563/
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-08-26 15:03:20  来源:igfitidea点击:

Force focus on one element with an exception. (jQuery)

jqueryinputfocus

提问by Luke Burns

I have two input fields. I want to force the focus on #area no matter where the user clicks unlessit is on #input. I've tried something like this, but since input is part of document, it does not work.

我有两个输入字段。无论用户点击哪里,我都想强制关注#area,除非它在#input上。我试过这样的事情,但由于输入是文档的一部分,它不起作用。

$("#area").focus();
$(document).click(function() { $("#area").focus() };
$("#input").click(function() { $("#input").focus() };

Thoughts?

想法?

回答by Gabriele Petrioli

change it to

将其更改为

$("#area").focus();
$(document).click(function() { $("#area").focus() });
$("#input").click(function(e) { e.stopPropagation(); $("#input").focus() });

This will stop the event from bubbling up to the document, and will only be caught by the #input

这将阻止事件冒泡到文档,并且只会被捕获 #input

回答by Weston C

The stopPropogationsolution is simpler than what I'm about to suggest, but it's probably worth discussing this other option. In that first function you've got, you might try taking the first argument to the function, which is a jQuery normalized event object:

stopPropogation解决方案比我将要建议的要简单,但可能值得讨论这个其他选项。在您拥有的第一个函数中,您可以尝试将该函数的第一个参数,它是一个 jQuery 规范化事件对象:

$(document).click(function(event) { ...

and testing it to see if the targetproperty of the event is your input:

并测试它以查看target事件的属性是否是您的输入:

$(document).click(function(event) {
    if(! (event.target == $("#input").get(0)) )
        $("#area").focus();
}

回答by Peter Kruithof

You need to cancel the event bubbling when clicking on the normal inputs, either by returning false in your event handler, or by calling e.stopPropagation().

单击正常输入时,您需要取消事件冒泡,方法是在事件处理程序中返回 false 或调用e.stopPropagation().

I'm not sure if the order in which you assign event handlers matters, but you might try to put the #inputevent first.

我不确定您分配事件处理程序的顺序是否重要,但您可能会尝试将#input事件放在首位。