开发者

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

开发者 https://www.devze.com 2023-02-25 22:15 出处:网络
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 mous

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 i开发者_C百科nnermost 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?


jQuery's event.target should do the trick:

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


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


:) 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(){
}
);
0

精彩评论

暂无评论...
验证码 换一张
取 消