是否有一个快速和简单的方法来做到这一点在jQuery,我错过了?
我不想使用鼠标悬停事件,因为我已经将它用于其他事情。我只需要知道鼠标在给定时刻是否在某个元素上。
我想做一些这样的事情,如果有一个“IsMouseOver”函数:
function hideTip(oi) {
setTimeout(function() { if (!IsMouseOver(oi)) $(oi).fadeOut(); }, 100);
}
是否有一个快速和简单的方法来做到这一点在jQuery,我错过了?
我不想使用鼠标悬停事件,因为我已经将它用于其他事情。我只需要知道鼠标在给定时刻是否在某个元素上。
我想做一些这样的事情,如果有一个“IsMouseOver”函数:
function hideTip(oi) {
setTimeout(function() { if (!IsMouseOver(oi)) $(oi).fadeOut(); }, 100);
}
当前回答
一个干净优雅的悬停检查:
if ($('#element:hover').length != 0) {
// do something ;)
}
其他回答
$(document).hover(function(e) {
alert(e.type === 'mouseenter' ? 'enter' : 'leave');
});
小提琴
这里有一个技术,它不依赖于jquery,并使用本机DOM匹配API。它使用厂商前缀支持回到IE9的浏览器。详情请参阅caniuse.com上的matchesselector。
首先创建matchesSelector函数,如下所示:
var matchesSelector = (function(ElementPrototype) {
var fn = ElementPrototype.matches ||
ElementPrototype.webkitMatchesSelector ||
ElementPrototype.mozMatchesSelector ||
ElementPrototype.msMatchesSelector;
return function(element, selector) {
return fn.call(element, selector);
};
})(Element.prototype);
然后,检测悬停:
var mouseIsOver = matchesSelector(element, ':hover');
在鼠标退出时设置超时以淡出并将返回值存储为对象中的数据。然后onmouseover,如果数据中有值,取消超时。
删除淡出的回调数据。
使用mouseenter/mouseleave实际上成本更低,因为当child鼠标悬停/鼠标退出触发时,它们不会触发菜单。
你可以使用is(':visible');在jquery 对于$('.item:hover'),它也在Jquery中工作。
这是一个HTM代码片段:
<li class="item-109 deeper parent">
<a class="root" href="/Comsopolis/index.php/matiers"><span>Matiers</span></a>
<ul>
<li class="item-110 noAff">
<a class=" item sousMenu" href="/Comsopolis/index.php/matiers/tsdi">
<span>Tsdi</span>
</a>
</li>
<li class="item-111 noAff">
<a class="item" href="/Comsopolis/index.php/matiers/reseaux">
<span>Réseaux</span>
</a>
</li>
</ul>
</li>
这是JS代码:
$('.menutop > li').hover(function() {//,.menutop li ul
$(this).find('ul').show('fast');
},function() {
if($(this).find('ul').is(':hover'))
$(this).hide('fast');
});
$('.root + ul').mouseleave(function() {
if($(this).is(':visible'))
$(this).hide('fast');
});
这就是我说的:)
这将是最简单的方法!
function(oi)
{
if(!$(oi).is(':hover')){$(oi).fadeOut(100);}
}