是否有一个快速和简单的方法来做到这一点在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);
}
当前回答
扩展什么'Happytime harry'说,一定要使用.data() jquery函数来存储超时id。这样,当'mouseenter'在同一个元素上被触发时,你可以很容易地检索超时id,允许你消除触发,让你的工具提示消失。
其他回答
你可以使用jQuery的mouseenter和mouseleave事件。您可以在鼠标进入所需区域时设置标志,并在鼠标离开该区域时取消设置标志。
我经常看到超时用于此,但在事件的上下文中,您不能像这样查看坐标吗?:
function areXYInside(e){
var w=e.target.offsetWidth;
var h=e.target.offsetHeight;
var x=e.offsetX;
var y=e.offsetY;
return !(x<0 || x>=w || y<0 || y>=h);
}
根据上下文,您可能需要在调用areXYInside(e)之前确保(this==e.t target)。
我正在考虑在dragLeave处理程序中使用这种方法,以确认dragLeave事件不是由进入子元素触发的。如果您没有以某种方式检查您是否仍然在父元素中,那么您可能会错误地执行仅在真正离开父元素时才执行的操作。
编辑:这是一个很好的想法,但并不能始终如一地工作。也许要做一些小调整。
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而不是横幅导航。
我完全理解更好的解决方案是重新设计横幅区域,这样就不会发生这种情况,但设计超出了我的控制范围。
警告:is(':hover')在jquery 1.8+中已弃用。请参阅这篇文章以获得解决方案。
你也可以使用这个答案:https://stackoverflow.com/a/6035278/8843来测试鼠标是否悬停在一个元素上:
$('#test').click(function() {
if ($('#hello').is(':hover')) {
alert('hello');
}
});
使用 evt.originalEvent.composedPath()
MouseEvent给出了鼠标最近与之交互的HTMLElement的数组。最后一个元素是最外层的(也就是说,它总是Window)。
MouseEvent composedPath()示例如下:
通过检查该数组中是否存在可点击的元素,您将知道是否在特定元素上有鼠标悬停…
$(window).on("mouseup", onMouseUp);
const $someButton = $("a.yourButton");
function onMouseUp(evt) {
const path = evt.originalEvent.composedPath();
if(path.indexOf($someButton[0]) !== -1){
// released mouse over button
}else{
// did not release mouse over button
}
}