[英]How do I check if focus has switched to a new element after another has blurred using jQuery?
I have a text input on my page. 我的页面上有文字输入。 When it receives focus, a select box appears underneath it. 当它获得焦点时,它下面会出现一个选择框。 When it loses focus, I want the select box to disappear unless the focus has shifted to the select box. 当它失去焦点时,我希望选择框消失, 除非焦点已移至选择框。 Sounds simple enough but I struck a problem. 听起来很简单,但我遇到了一个问题。
I set up the event handlers like so (using coffeescript) 我设置了这样的事件处理程序(使用coffeescript)
jQuery ->
$('td.description input').focus -> showItemSelector()
$('td.description input').blur -> hideItemSelector()
showItemSelector()
and hideItemSelector()
are defined like so showItemSelector()
和hideItemSelector()
的定义是这样的
showItemSelector () ->
$('#item-selector').show()
hideItemSelector () ->
unless $('#item-selector select').is(':focus')
$('#item-selector').hide()
But it doesn't work. 但它不起作用。 The item selector is always hidden after the input loses focus. 输入失去焦点后,项目选择器始终隐藏。 I did some experimenting and my suspicion was confirmed. 我做了一些实验,我的怀疑得到了证实。 The hideItemSelector
function is being executed before focus is shifted to the new element (which makes some sense - the browser presumably takes focus from the first element, triggering my function, before it assigns focus to the next element). hideItemSelector
函数在焦点转移到新元素之前执行(这hideItemSelector
意义 - 浏览器可能从第一个元素获取焦点,触发我的函数,然后将焦点分配给下一个元素)。 The following bit of code demonstrates this; 以下代码演示了这一点;
hideItemSelector = () ->
focus = -> console.log $('select#category').is(':focus')
focus()
setTimeout focus, 1000
This returns false and then true in the console. 这将在控制台中返回false,然后返回true。 The delay gives the browser time to shift the focus. 延迟使浏览器有时间转移焦点。
So my question is, how can I do what I want to do without using a setTimeout? 所以我的问题是,如何在不使用setTimeout的情况下做我想做的事情? If nothing else works then this will have to do, but it seems like a flawed approach. 如果没有其他工作,那么这将是必须的,但它似乎是一个有缺陷的方法。
You can achieve this with assigning global var and changing its value from true
to false
as a user moves on and off the object, for example: 您可以通过分配全局变量并在用户移动和移动对象时将其值从true
更改为false
来实现此目的,例如:
$('#yourElement').mouseenter(function() {
isHovered = true;
}).mouseleave(function() {
isHovered = false;
});
There is also a way that works in all browsers except Internet Explorer but I wouldn't recommend using it as it's using invalid pseudo-selector: 还有一种方法适用于除Internet Explorer之外的所有浏览器,但我不建议使用它,因为它使用无效的伪选择器:
if ($('#hello').is(':hover')) {
alert('hello');
}
Other than that you will have to find plugins for that. 除此之外,你将不得不找到插件。 Here is the self made plugin by SpYk3HH which can be found here: jsFiddle isHover Plugin Demo . 这是SpYk3HH自制的插件,可以在这里找到: jsFiddle isHover插件演示 。 I would also recommend reading: How do I check if the mouse is over an element in jQuery? 我还建议阅读: 如何检查鼠标是否在jQuery中的元素上? . 。 I think it will be useful to you. 我认为这对你有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.