强制聚焦于一个元素,但有例外。 (jQuery)
我有两个输入字段。我想强制将焦点放在#area 上,无论用户在哪里单击除非是在#input 上。我已经尝试过类似的方法,但由于输入是文档的一部分,因此它不起作用。
$("#area").focus();
$(document).click(function() { $("#area").focus() };
$("#input").click(function() { $("#input").focus() };
想法?
I have two input fields. I want to force the focus on #area no matter where the user clicks unless it is on #input. I've tried something like this, but since input is part of document, it does not work.
$("#area").focus();
$(document).click(function() { $("#area").focus() };
$("#input").click(function() { $("#input").focus() };
Thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将其更改为
这将阻止事件冒泡到文档,并且只会被
#input
捕获change it to
This will stop the event from bubbling up to the document, and will only be caught by the
#input
stopPropogation
解决方案比我要建议的更简单,但可能值得讨论这个其他选项。在您拥有的第一个函数中,您可以尝试将第一个参数传递给函数,这是一个 jQuery 规范化事件对象:并测试它以查看事件的
target
属性是否是您的输入:The
stopPropogation
solution 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:and testing it to see if the
target
property of the event is your input:单击正常输入时,您需要取消事件冒泡,方法是在事件处理程序中返回 false,或者调用
e.stopPropagation()
。我不确定分配事件处理程序的顺序是否重要,但您可以尝试将
#input
事件放在第一位。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()
.I'm not sure if the order in which you assign event handlers matters, but you might try to put the
#input
event first.