is(“:hover")仅在setInterval函数内工作 [英] is(":hover") only working within a setInterval function
问题描述
请参阅 https://jsfiddle.net/cot33dxa/
setInterval(function() {
if ($("#one").is(":hover")) {
$("#one").css("background-color", "red");
} else {
$("#one").css("background-color", "");
}
}, 0);
if ($("#two").is(":hover")) {
$("#two").css("background-color", "blue");
} else {
$("#two").css("background-color", "");
}
#one {
width: 200px;
height: 200px;
background-color: yellow;
}
#two {
width: 200px;
height: 200px;
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="one"></div>
<div id="two"></div>
为什么对于第一个div来说,悬停检查工作得很好,而在第二个div中却不能呢?
Why is it that for div one, the hover check works just fine, whereas it doesn't in div two?
使用if ($('#element:hover').length != 0)
时,我遇到相同的问题(摘自 ivo的解决方案).
I have the same issue when using if ($('#element:hover').length != 0)
(taken from ivo's solution).
为此的JS提琴手: https://jsfiddle.net/q8dfLc6s/
从更一般的意义上讲,我正在寻找最简单,最可靠的方法来了解鼠标是否位于JQuery 1.11.0中的div上方.就目前情况而言,除了这个SetInterval奇数之外,我什至无法使布尔检查完全起作用.
In a more general sense, I am looking for the simplest, most reliable way to know if the mouse is over a div in JQuery 1.11.0. As it stands, I can't even get the boolean check to work at all aside from this SetInterval oddity.
推荐答案
小提琴的问题在于您的第二次检查不在间隔函数之内.试试这个:
The problem with your fiddle is that your second check is outside of your interval function. Try this:
setInterval(function(){
if($("#one").is(":hover")) {
$("#one").css("background-color","red");
}
else {
$("#one").css("background-color","");
}
if($("#two").is(":hover")) {
$("#two").css("background-color","blue");
}
else {
$("#two").css("background-color","");
}
},0);
这篇关于is(“:hover")仅在setInterval函数内工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!