how do I know if the mouse pointer is on the HTML element?

百般思念 提交于 2019-12-11 02:23:09

问题


I have a timed event I want to behave differently accordingly to what HTML element the mouse pointer is on.
Is there a way, assuming I have the HTML element, to know if the mouse pointer is currently on top of it.
I am well aware of the onmouseover/onmouseout events and how to use them.
I am using JQuery.
I am obviously looking for some kind of flag, as I need to check a state and not handle an event.
again, I know how to implement this with events.


回答1:


I'm not aware of any built-in way to ping an element for the status of mouse hovering.

However, you can create one by updating a flag at mouseenter and mouseleave -- which is where Brian Driscoll's suggestion of .hover comes in:

jQuery.fn.tracking = function () {
  this.data('hovering', false);

  this.hover(function () {
    $(this).data('hovering', true);
  }, function () {
    $(this).data('hovering', false);
  });

  return this;
};

jQuery.fn.hovering = function () {
  return this.data('hovering');
}

You'll need to initialize tracking for each element you care about:

$('#elem1,#elem2').tracking();

But then you can get the status of any of them:

if ($('#elem1').hovering()) {
    // ...
} else if ($('#elem2').hovering()) {
    // ...
}

Demo: http://jsbin.com/amaxu3/edit




回答2:


Have you looked into jQuery.hover()? http://api.jquery.com/hover/




回答3:


You need to give name to html andme and on mouseover you need to check document.getelementsbyName. Then check what your are getting as output. Now you can take decision is it html control or asp.net.

When you use collObjects = object.getElementsByName("htmlcontrol") then compare id of both.

1 morething why you needed to check this in javascript. there may be some other solution for that. Just share with us.




回答4:


You might have some luck with document.elementFromPoint, although I believe there are some inconsistencies in older browser implementations (http://www.quirksmode.org/dom/w3c_cssom.html#documentview).

$('#elem').mousemove(function(e){
    if (this == document.elementFromPoint(e.clientX, e.clientY)) {
        // Do stuff
    }
});

Or outside of a handler

if ($('#elem').get(0) == document.elementFromPoint(x, y)) {
    // Do stuff
}

Aside from that, the only other option that comes to mind is using event handlers to keep track of which element the mouse is over.



来源:https://stackoverflow.com/questions/3399647/how-do-i-know-if-the-mouse-pointer-is-on-the-html-element

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