javascript 检查此元素或此元素是否用 jQuery 悬停
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20076609/
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
check if this element OR this element is hovered with jQuery
提问by Ty Bailey
I have two separate elements in my DOM that require a change when either one is hovered. When the link is hovered, the image src needs to change (easy) AND the link color needs to change. When the image is hovered, the same effect needs to happen (image src changes & link color changes)
我的 DOM 中有两个单独的元素,当悬停其中一个时需要更改。当链接悬停时,图像 src 需要更改(简单)并且链接颜色需要更改。当图片被悬停时,同样的效果需要发生(图片src变化&链接颜色变化)
This is actually quite easy to do, but I have a feeling there is a MUCH easier way to do it then the approach I am taking. Currently I am going through each of the 8 elements and testing if they are hovered individually. This works good, but there is so much more jQuery here than I feel there should be.
这实际上很容易做到,但我觉得有一种比我正在采取的方法更简单的方法。目前我正在浏览 8 个元素中的每一个,并测试它们是否单独悬停。这很好用,但是这里的 jQuery 比我觉得应该多得多。
I tried adding the attribute onmouseover
to both of the elements and triggering the same function, but for some reason the function wasn't triggering.
我尝试将属性添加onmouseover
到两个元素并触发相同的功能,但由于某种原因,该功能没有触发。
Is there a way to test if either element is hovered and trigger a function if either one is? Something like this:
有没有办法测试是否有任何一个元素被悬停并触发一个函数(如果有一个是)?像这样的东西:
if($(#elm1).hover() || $('#elm2').hover()) {
//effect here
}
OR
或者
if($('#elm1').is(':hover') || $('#elm2').is(':hover')) {
//effect here
}
I tried my example code above, but wasn't getting any results. Is there a way to do this or am I stuck with checking each individual element?
我尝试了上面的示例代码,但没有得到任何结果。有没有办法做到这一点,还是我坚持检查每个单独的元素?
回答by Zach Saucier
It works, you're just running it on page load, not when the mouse moves
它有效,您只是在页面加载时运行它,而不是在鼠标移动时
$(document).mousemove(function() {
if($('#elm1').is(':hover') || $('#elm2').is(':hover')) {
// Do stuff
}
else {
// Revert do stuff or do other stuff
}
});
But, as other's have said, jQuery already knows the hover
state, so doing it this way would be unnecessary. In practice you should use the same selector to apply the function to it
但是,正如其他人所说,jQuery 已经知道hover
状态,所以这样做是没有必要的。在实践中,您应该使用相同的选择器将函数应用于它
$('#idOne, #idTwo').hover(function() { /* Do stuff */ });
回答by inputError
I would register events on mouseover and whenever the event happens trigger a function
我会在鼠标悬停时注册事件,每当事件发生时都会触发一个函数
$("#elm1, #elm2").on("mouseover", function () {
// effect here
});
回答by Pat Dobson
Why not simply add the handler to both elements like this :
为什么不像这样简单地将处理程序添加到两个元素中:
$('#elm1, #elm2').hover(function(){
// ... do stuff here ...
});
Should work . . .
应该管用 。. .