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

前端 未结 24 2632
不思量自难忘°
不思量自难忘° 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:15

    I needed something exactly as this (in a little more complex environment and the solution with a lot of 'mouseenters' and 'mouseleaves' wasnt working properly) so i created a little jquery plugin that adds the method ismouseover. It has worked pretty well so far.

    //jQuery ismouseover  method
    (function($){ 
        $.mlp = {x:0,y:0}; // Mouse Last Position
        function documentHandler(){
            var $current = this === document ? $(this) : $(this).contents();
            $current.mousemove(function(e){jQuery.mlp = {x:e.pageX,y:e.pageY}});
            $current.find("iframe").load(documentHandler);
        }
        $(documentHandler);
        $.fn.ismouseover = function(overThis) {  
            var result = false;
            this.eq(0).each(function() {  
                    var $current = $(this).is("iframe") ? $(this).contents().find("body") : $(this);
                    var offset = $current.offset();             
                    result =    offset.left<=$.mlp.x && offset.left + $current.outerWidth() > $.mlp.x &&
                                offset.top<=$.mlp.y && offset.top + $current.outerHeight() > $.mlp.y;
            });  
            return result;
        };  
    })(jQuery);
    

    Then in any place of the document yo call it like this and it returns true or false:

    $("#player").ismouseover()
    

    I tested it on IE7+, Chrome 1+ and Firefox 4 and is working properly.

提交回复
热议问题