Javascript 使用jQuery检测悬停在元素上的IF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8981463/
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
Detect IF hovering over element with jQuery
提问by James Skidmore
I'm not looking for an action to call whenhovering, but instead a way to tell ifan element is being hovered over currently. For instance:
我不是在寻找一个行动调用的时候徘徊,而是要告诉的方式,如果一个元素正在上空盘旋目前。例如:
$('#elem').mouseIsOver(); // returns true or false
Is there a jQuery method that accomplishes this?
是否有实现此目的的 jQuery 方法?
回答by Meligy
Original (And Correct) Answer:
原始(和正确)答案:
You can use is()
and check for the selector :hover
.
您可以使用is()
并检查选择器:hover
。
var isHovered = $('#elem').is(":hover"); // returns true or false
Example: http://jsfiddle.net/Meligy/2kyaJ/3/
示例:http: //jsfiddle.net/Meligy/2kyaJ/3/
(This only works when the selector matches ONE element max. See Edit 3 for more)
(这仅在选择器最多匹配一个元素时才有效。有关更多信息,请参阅编辑 3)
.
.
Edit 1 (June 29, 2013):(Applicable to jQuery 1.9.x only, as it works with 1.10+, see next Edit 2)
编辑 1(2013 年 6 月 29 日):(仅适用于 jQuery 1.9.x,因为它适用于 1.10+,请参阅下一个编辑 2)
This answer was the best solution at the time the question was answered. This ':hover' selector was removed with the .hover()
method removal in jQuery 1.9.x.
这个答案是回答问题时的最佳解决方案。这个 ':hover' 选择器随着.hover()
jQuery 1.9.x 中的方法删除而被删除。
Interestingly a recent answer by "allicarn" shows it's possible to use :hover
as CSS selector (vs. Sizzle) when you prefix it with a selector $($(this).selector + ":hover").length > 0
, and it seems to work!
有趣的是,“allicarn”最近的一个回答表明,:hover
当您使用 selector 前缀时,可以将其用作 CSS 选择器(与 Sizzle 相比)$($(this).selector + ":hover").length > 0
,并且它似乎有效!
Also, hoverIntentplugin mentioned in a another answer looks very nice as well.
另外,另一个答案中提到的hoverIntent插件看起来也很不错。
Edit 2 (September 21, 2013):.is(":hover")
works
编辑 2(2013 年 9 月 21 日):.is(":hover")
作品
Based on another comment I have noticed that the original way I posted, .is(":hover")
, actually still works in jQuery, so.
根据另一条评论,我注意到我发布的原始方式.is(":hover")
实际上仍然适用于 jQuery,所以。
It worked in jQuery 1.7.x.
It stopped working in 1.9.1, when someone reported it to me, and we all thought it was related to jQuery removing the
hover
alias for event handling in that version.It worked again in jQuery 1.10.1 and 2.0.2 (maybe 2.0.x), which suggests that the failure in 1.9.x was a bug or so not an intentional behaviour as we thought in the previous point.
它适用于 jQuery 1.7.x。
它在 1.9.1 中停止工作,当有人向我报告时,我们都认为这与 jQuery 删除了
hover
该版本中事件处理的别名有关。它在 jQuery 1.10.1 和 2.0.2(可能是 2.0.x)中再次起作用,这表明 1.9.x 中的失败是一个错误,而不是我们在前一点中认为的有意行为。
If you want to test this in a particular jQuery version, just open the JSFidlle example at the beginning of this answer, change to the desired jQuery version and click "Run". If the colour changes on hover, it works.
如果您想在特定的 jQuery 版本中对此进行测试,只需打开本答案开头的 JSFiddle 示例,更改为所需的 jQuery 版本并单击“运行”。如果悬停时颜色发生变化,则它起作用。
.
.
Edit 3 (March 9, 2014): It only works when the jQuery sequence contains a single element
编辑 3(2014 年 3 月 9 日):仅当 jQuery 序列包含单个元素时才有效
As shown by @Wilmer in the comments, he has a fiddle which doesn't even work against jQuery versions I and others here tested it against. When I tried to find what's special about his case I noticed that he was trying to check multiple elements at a time. This was throwing Uncaught Error: Syntax error, unrecognized expression: unsupported pseudo: hover
.
正如@Wilmer 在评论中所示,他有一个小提琴,它甚至不适用于我和其他人在这里测试的 jQuery 版本。当我试图找出他的案例有什么特别之处时,我注意到他试图一次检查多个元素。这是在扔Uncaught Error: Syntax error, unrecognized expression: unsupported pseudo: hover
。
So, working with his fiddle, this does NOTwork:
所以,他的小提琴的工作,但这不工作:
var isHovered = !!$('#up, #down').filter(":hover").length;
While this DOESwork:
虽然这确实有效:
var isHovered = !!$('#up,#down').
filter(function() { return $(this).is(":hover"); }).length;
It also works with jQuery sequences that contain a single element, like if the original selector matched only one element, or if you called .first()
on the results, etc.
它也适用于包含单个元素的 jQuery 序列,例如原始选择器是否仅匹配一个元素,或者您是否调用.first()
了结果等。
This is also referenced at my JavaScript + Web Dev Tips & Resources Newsletter.
回答by user2444818
Use:
用:
var hovered = $("#parent").find("#element:hover").length;
jQuery 1.9+
jQuery 1.9+
回答by allicarn
It does not work in jQuery 1.9. Made this plugin based on user2444818's answer.
它在 jQuery 1.9 中不起作用。根据 user2444818 的回答制作了这个插件。
jQuery.fn.mouseIsOver = function () {
return $(this).parent().find($(this).selector + ":hover").length > 0;
};
回答by Mino
You can filter your elment from all hovered elements. Problematic code:
您可以从所有悬停的元素中过滤您的元素。有问题的代码:
element.filter(':hover')
Save code:
保存代码:
jQuery(':hover').filter(element)
To return boolean:
返回布尔值:
jQuery(':hover').filter(element).length===0
回答by gidim
The accepted answer didn't work for me on JQuery 2.x
.is(":hover")
returns false on every call.
接受的答案在 JQuery 2.x 上对我不起作用,
.is(":hover")
每次调用都返回 false。
I ended up with a pretty simple solution that works:
我最终得到了一个非常简单的解决方案:
function isHovered(selector) {
return $(selector+":hover").length > 0
}
回答by kinakuta
Set a flag on hover:
在悬停时设置标志:
var over = false;
$('#elem').hover(function() {
over = true;
},
function () {
over = false;
});
Then just check your flag.
然后只需检查您的标志。
回答by Donald A Nummer Jr
Couple updates to add after working on this subject for a while:
在研究这个主题一段时间后要添加的一些更新:
- all solutions with .is(":hover") break on jQuery 1.9.1
- The most likely reason to check if the mouse is still over an element is to attempt to prevent events firing over each other. For example, we were having issues with our mouseleave being triggered and completed before our mouseenter event even completed. Of course this was because of a quick mouse movement.
- 所有带有 .is(":hover") 的解决方案都在 jQuery 1.9.1 上中断
- 检查鼠标是否仍在元素上的最可能原因是试图防止事件相互触发。例如,在我们的 mouseenter 事件完成之前,我们的 mouseleave 就被触发并完成了。当然,这是因为鼠标的快速移动。
We used hoverIntent https://github.com/briancherne/jquery-hoverIntentto solve the issue for us. Essentially it triggers if the mouse movement is more deliberate. (one thing to note is that it will trigger on both mouse entering an element and leaving - if you only want to use one pass the constructor an empty function )
我们使用hoverIntent https://github.com/briancherne/jquery-hoverIntent为我们解决了这个问题。本质上,如果鼠标移动更加刻意,它就会触发。(要注意的一件事是,它会在鼠标进入元素和离开时触发 - 如果您只想使用一个传递构造函数一个空函数)
回答by gideon
Expanding on @Mohamed's answer. You could use a little encapsulation
扩展@Mohamed 的回答。你可以使用一点封装
Like this:
像这样:
jQuery.fn.mouseIsOver = function () {
if($(this[0]).is(":hover"))
{
return true;
}
return false;
};
Use it like:
像这样使用它:
$("#elem").mouseIsOver();//returns true or false
Forked the fiddle: http://jsfiddle.net/cgWdF/1/
分叉小提琴:http: //jsfiddle.net/cgWdF/1/
回答by molokoloco
I like the first response, but for me it's weird. When attempting to check just after page load for the mouse, I have to put in at least a 500 millisecond delay for it to work:
我喜欢第一反应,但对我来说这很奇怪。当试图在页面加载后检查鼠标时,我必须至少延迟 500 毫秒才能使其工作:
$(window).on('load', function() {
setTimeout(function() {
$('img:hover').fadeOut().fadeIn();
}, 500);
});
回答by RobG
Setting a flag per kinakuta's answer seems reasonable, you can put a listener on the body so you can check if any element is being hovered over at a particular instant.
为每个 kinakuta 的答案设置一个标志似乎是合理的,您可以在 body 上放置一个监听器,这样您就可以检查是否有任何元素在特定时刻悬停在上面。
However, how do you want to deal with child nodes? You should perhaps check if the element is an ancestor of the currently hovered element.
但是,您希望如何处理子节点?您或许应该检查该元素是否是当前悬停元素的祖先。
<script>
var isOver = (function() {
var overElement;
return {
// Set the "over" element
set: function(e) {
overElement = e.target || e.srcElement;
},
// Return the current "over" element
get: function() {
return overElement;
},
// Check if element is the current "over" element
check: function(element) {
return element == overElement;
},
// Check if element is, or an ancestor of, the
// current "over" element
checkAll: function(element) {
while (overElement.parentNode) {
if (element == overElement) return true;
overElement = overElement.parentNode;
}
return false;
}
};
}());
// Check every second if p0 is being hovered over
window.setInterval( function() {
var el = document.getElementById('p0');
document.getElementById('msg').innerHTML = isOver.checkAll(el);
}, 1000);
</script>
<body onmouseover="isOver.set(event);">
<div>Here is a div
<p id="p0">Here is a p in the div<span> here is a span in the p</span> foo bar </p>
</div>
<div id="msg"></div>
</body>