javascript 使用 jQuery 检查 mouseleave() 时光标所在的元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7761117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:13:13  来源:igfitidea点击:

Check what element the cursor is on upon mouseleave() with jQuery?

javascriptjquerynestedmouseovermouseleave

提问by Tyler Nieman

I have a set of list elements (<li>within a <ul>) laid out as bubbles on a chart like this, where the bubbles are the <li>elements:

我有一组列表元素(<li>在 a 内<ul>)在像这样的图表上布置为气泡,其中气泡是<li>元素:

http://i.stack.imgur.com/PR7vR.png

http://i.stack.imgur.com/PR7vR.png

I want to be able to detect the difference between

我希望能够检测到之间的差异

  1. Moving the mouse from bubble #1 to the grid
  2. Moving the mouse from bubble #1 directly toanother bubble, such as bubble 2
  1. 将鼠标从气泡 #1 移动到网格
  2. 将鼠标从气泡 #1直接移动到另一个气泡,例如气泡 2

I've attempted to use $(this)in the .mouseleave()even for a bubble, but it registers the element that you're leaving rather than the element that you're currently hovering.

我试图$(this).mouseleave()偶数中使用气泡,但它注册了您要离开的元素,而不是您当前悬停的元素。

Any ideas on how to get the element that the mouse is moving onto upon mouseleave()?

关于如何获取鼠标移动到的元素的任何想法mouseleave()

回答by N Rohler

You need to use event.toElement || e.relatedTarget:

你需要使用event.toElement || e.relatedTarget

$('li').mouseleave(function(e)
{
    // new element is: e.toElement || e.relatedTarget
});

(Edited to note || e.relatedTargetto ensure browser compatibility)

(编辑注意|| e.relatedTarget以确保浏览器兼容性)

回答by kennebec

If you can use ordinarey javascript, every event (e) mouse over and mouse out has an e.relatedTarget in most browsers. IE before #9 has event.toElement and event.fromElement, depending on if you are listening to a mouseover or mouseout.

如果您可以使用 ordinarey javascript,则在大多数浏览器中,每个事件 (e) 鼠标悬停和鼠标移出都有一个 e.relatedTarget。#9 之前的 IE 有 event.toElement 和 event.fromElement,这取决于你是在监听鼠标悬停还是鼠标移开。

somebody.onmouseout=function(e){
  if(!e && window.event)e=event;
  var goingto=e.relatedTarget|| event.toElement;
  //do something
}
somebody.onmouseover=function(e){
  if(!e && window.event)e=event;
  var comingfrom=e.relatedTarget|| e.fromElement;
  //do something
}