How do I check if the mouse is over an element in jQuery?

前端 未结 24 2457
不思量自难忘°
不思量自难忘° 2020-11-22 08:10

Is there a quick & easy way to do this in jQuery that I\'m missing?

I don\'t want to use the mouseover event because I\'m already using it for something else. I

24条回答
  •  执念已碎
    2020-11-22 09:09

    Here's a technique which doesn't rely on jquery and uses the native DOM matches API. It uses vendor prefixes to support browsers going back to IE9. See matchesselector on caniuse.com for full details.

    First create the matchesSelector function, like so:

    var matchesSelector = (function(ElementPrototype) {
    var fn = ElementPrototype.matches ||
              ElementPrototype.webkitMatchesSelector ||
              ElementPrototype.mozMatchesSelector ||
              ElementPrototype.msMatchesSelector;
    
    return function(element, selector) {
      return fn.call(element, selector);
    };
    
    })(Element.prototype);
    

    Then, to detect hover:

    var mouseIsOver = matchesSelector(element, ':hover');
    

提交回复
热议问题