jQuery: how to get the innermost dom element I'm hovering over, globally for the whole document body?

百般思念 提交于 2019-12-07 14:49:37

问题


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.

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?


回答1:


jQuery's event.target should do the trick:

$("body").click(function(event) {
  console.log($(event.target));
});



回答2:


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);
  }
});



回答3:


:) think of all the elements, Like:

<div>this is div</div>
<span>this is span</span>
<p>This is p</p>
<a>this a</a>
<ul><li>this is ul li</li></ul>
<ol><li>This is ol li</li></ol>
<img src="" />
<textarea id="text"></textarea>

The textarea is to show you the result only.

jQuery("div,span,p,a,ul,ol,img").hover(function(){
    jQuery("#text").append(jQuery(this).html() + 
                           "<br />");
},function(){
}
);


来源:https://stackoverflow.com/questions/5693015/jquery-how-to-get-the-innermost-dom-element-im-hovering-over-globally-for-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!