How can I find current element on mouseover using jQuery?

前端 未结 8 1730
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-24 07:10

How can I get the class name of the current element that is on mouseover? For example \"enter<

相关标签:
8条回答
  • 2020-12-24 07:50

    Get the position of element on mouseover and then get the class name

    <div id="wrapper">
    <a href="#" class="anchorClass">A</a><div class="divClass">DIV</div>
    </div>
    
    $('#wrapper').mouseover(function(e) {
        var x = e.clientX, y = e.clientY,
            elementOnMouseOver = document.elementFromPoint(x, y);
            elementClass=$(elementOnMouseOver).attr('class');
        alert(elementClass);
    });
    

    JSFiddle: http://jsfiddle.net/ankur1990/kUyE7/

    If you don't want to apply this only on wrapper div but on whole window/document, then you can replace wrapper with window/document

     $(window).mouseover(function(e){});
    
    0 讨论(0)
  • 2020-12-24 07:51

    All depending on how you want it. This could also be an option:

    »Fiddle 1«

    With some more detail. This will only show as true after taking the direct path from a to div. (The tiny white space between a and div.) As in:

    • a -> div TRUE
    • a -> div -> white space in between -> div FALSE

    »Fiddle 2«

    Might hold up. This will also show as true if one go to the tiny white space between a and div, and then go back to div. As in:

    • a -> div -> white space in between -> div TRUE

    var mode = 0;
    $(window).on("mousemove", function(e) {
        if (e.target.className === "d1") {
            mode = 1;   
        } else {
            var cc = e.target.className;
            if (cc !== "d2" && mode) {
                var el = $(".d1"),
                    d1 = {
                        x : el.offset().left,
                        y : el.offset().top,
                        w : el.width(),
                        h : el.height()
                    },
                    c = {
                        x  : e.pageX,
                        y  : e.pageY
                    };
                if (c.x >= d1.x + d1.w && c.y >= d1.y && c.y <= d1.y + d1.h)
                    mode = 2;
                else
                    mode = 0;
            } else if (cc === "d2" && mode) {
                mode = 3;
            }
        }
        $("#status").html("Current: " + (mode == 3 ? "OVER" : "NOT OVER") + " from a" );
    });
    
    0 讨论(0)
提交回复
热议问题