是否有一个快速和简单的方法来做到这一点在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);
}
当前回答
For those like me who needed an answer that didn't depend on browser mouse-over/enter/leave events or hover states. I had a situation in a home-page slider, the left and right slide click areas could overlap (or sometimes completely cover) the CTA buttons in the banner - this renders all those previous methods useless (browser only reports events on the element with the highest z-index). I was tasked with making the click event care more about the button than the banner functionality when the click is over the button.
我的完整解是这样的:
jQuery('.carousel-control-prev').on('click.testClick', function(e) {
var bannerButtons = jQuery('.banner-content a');
for (var i = 0; i < bannerButtons.length; i++) {
if (isMouseOver(bannerButtons.eq(i), e)) {
e.preventDefault();
e.stopPropagation();
bannerButtons[i].click();
}
}
});
function isMouseOver($el, e) {
if ($el.is(':visible')) {
var offset = $el.offset();
var x = (e.pageX - offset.left);
var y = (e.pageY - offset.top);
if (x > 0 && x < $el.outerWidth() && y > 0 && y < $el.outerHeight()) {
return true;
}
}
return false;
}
这可能需要更多的工作和测试,但现在它做了我需要的-在这种情况下是拦截横幅左键点击,检查鼠标是否恰好在CTA按钮上,如果是,点击CTA而不是横幅导航。
我完全理解更好的解决方案是重新设计横幅区域,这样就不会发生这种情况,但设计超出了我的控制范围。
其他回答
$(document).hover(function(e) {
alert(e.type === 'mouseenter' ? 'enter' : 'leave');
});
小提琴
这段代码说明了我和harry想要表达的意思。当鼠标进入时,会出现一个工具提示,当鼠标离开时,它会为工具提示的消失设置一个延迟。如果鼠标在触发延迟之前输入了相同的元素,那么我们使用之前存储的数据在触发器触发之前销毁它。
$("someelement").mouseenter(function(){
clearTimeout($(this).data('timeoutId'));
$(this).find(".tooltip").fadeIn("slow");
}).mouseleave(function(){
var someElement = $(this),
timeoutId = setTimeout(function(){
someElement.find(".tooltip").fadeOut("slow");
}, 650);
//set the timeoutId, allowing us to clear this trigger if the mouse comes back over
someElement.data('timeoutId', timeoutId);
});
上面Arthur Goldsmith的回答很流行也很有用:如果你在IE中将鼠标从一个元素移动到另一个元素(至少在IE 9之前),如果新元素的背景是透明的(默认情况下是透明的),你可能会遇到一些麻烦。我的解决办法是给新元素一个透明的背景图像。
在鼠标退出时设置超时以淡出并将返回值存储为对象中的数据。然后onmouseover,如果数据中有值,取消超时。
删除淡出的回调数据。
使用mouseenter/mouseleave实际上成本更低,因为当child鼠标悬停/鼠标退出触发时,它们不会触发菜单。
你可以使用jQuery的悬停事件来手动跟踪:
$(...).hover(
function() { $.data(this, 'hover', true); },
function() { $.data(this, 'hover', false); }
).data('hover', false);
if ($(something).data('hover'))
//Hovered!