是否有一个快速和简单的方法来做到这一点在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);
}
当前回答
我结合了这个主题的想法,想出了这个,这对于显示/隐藏子菜单很有用:
$("#menu_item_a").mouseenter(function(){
clearTimeout($(this).data('timeoutId'));
$("#submenu_a").fadeIn("fast");
}).mouseleave(function(){
var menu_item = $(this);
var timeoutId = setTimeout(function(){
if($('#submenu_a').is(':hover'))
{
clearTimeout(menu_item.data('timeoutId'));
}
else
{
$("#submenu_a").fadeOut("fast");
}
}, 650);
menu_item.data('timeoutId', timeoutId);
});
$("#submenu_a").mouseleave(function(){
$(this).fadeOut("fast");
});
似乎对我有用。希望这能帮助到一些人。
编辑:现在意识到这种方法在IE中不能正确工作。
其他回答
我需要的东西正是这样的(在一个更复杂的环境和解决方案有很多'mouseenter '和'mouseleaves'没有正常工作),所以我创建了一个小jquery插件,添加方法ismouseover。到目前为止,它运行得很好。
//jQuery ismouseover method
(function($){
$.mlp = {x:0,y:0}; // Mouse Last Position
function documentHandler(){
var $current = this === document ? $(this) : $(this).contents();
$current.mousemove(function(e){jQuery.mlp = {x:e.pageX,y:e.pageY}});
$current.find("iframe").load(documentHandler);
}
$(documentHandler);
$.fn.ismouseover = function(overThis) {
var result = false;
this.eq(0).each(function() {
var $current = $(this).is("iframe") ? $(this).contents().find("body") : $(this);
var offset = $current.offset();
result = offset.left<=$.mlp.x && offset.left + $current.outerWidth() > $.mlp.x &&
offset.top<=$.mlp.y && offset.top + $current.outerHeight() > $.mlp.y;
});
return result;
};
})(jQuery);
然后在文档的任何地方像这样调用它,它会返回true或false:
$("#player").ismouseover()
我在IE7+、Chrome 1+和Firefox 4上进行了测试,运行正常。
这里有一个技术,它不依赖于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');
警告:is(':hover')在jquery 1.8+中已弃用。请参阅这篇文章以获得解决方案。
你也可以使用这个答案:https://stackoverflow.com/a/6035278/8843来测试鼠标是否悬停在一个元素上:
$('#test').click(function() {
if ($('#hello').is(':hover')) {
alert('hello');
}
});
扩展什么'Happytime harry'说,一定要使用.data() jquery函数来存储超时id。这样,当'mouseenter'在同一个元素上被触发时,你可以很容易地检索超时id,允许你消除触发,让你的工具提示消失。
在鼠标退出时设置超时以淡出并将返回值存储为对象中的数据。然后onmouseover,如果数据中有值,取消超时。
删除淡出的回调数据。
使用mouseenter/mouseleave实际上成本更低,因为当child鼠标悬停/鼠标退出触发时,它们不会触发菜单。