jQuery:如何获取我悬停的最里面的 dom 元素,全局用于整个文档正文?

2022-01-22 00:00:00 mouseevent hover jquery javascript

我想检测鼠标在整个文档正文上的移动,并能够准确判断我悬停在 DOM 的哪个部分.哪一部分"是指鼠标当前所在的最里面的 DOM 元素.

I'd like to detect mouse movements over the whole document body, and be able to tell exactly which part of the DOM I'm hovering over. By "Which part" I mean the innermost DOM element that the mouse is currently over.

我可以将悬停绑定到整个文档正文,但是 $(this) 会给我 $(body),而不是最里面的元素.或者我可以递归地遍历整个 DOM 并将悬停绑定到每个元素,但这将是一个严重的过度杀伤 IMO.

I could bind a hover to the whole document body, but then the $(this) would give me the $(body), not the innermost element. Or I could iterate over the whole DOM recursively and bind a hover to each elements, but that would be a serious overkill IMO.

有没有简单的方法来实现这一点?

Is there an easy way to achieve this?

推荐答案

根据 Jasie 的建议,我最终使用了以下代码:

Based on Jasie's suggestion, I ended up using the following code:

var currentNode = null;
$('body').mousemove(function(event) {
  if ($(event.target) !== currentNode) {
    currentNode = $(event.target);
    console.log(currentNode);
  }
});

相关文章