jQuery:如何获取我悬停的最里面的 dom 元素,全局用于整个文档正文? [英] jQuery: how to get the innermost dom element I'm hovering over, globally for the whole document body?

查看:14
本文介绍了jQuery:如何获取我悬停的最里面的 dom 元素,全局用于整个文档正文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检测鼠标在整个文档正文上的移动,并能够准确判断我悬停在 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);
  }
});

这篇关于jQuery:如何获取我悬停的最里面的 dom 元素,全局用于整个文档正文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆