How can I check if the cursor is hovering on an element using JQuery

前端 未结 5 1041
离开以前
离开以前 2021-02-18 17:38

It possible to check if the cursor is hovering on an element.

Something like

 $(\"#divId\").is(\"hover\");

NOTE: I just want to check n

5条回答
  •  别那么骄傲
    2021-02-18 18:25

    You can use jQuery's hover(), mouseenter() or mouseover()

    $("#divId").hover(function() { alert("hovering"; });
    

    This will fire on mouseenter and mouseleave. You can add separate event handlers for each.

    So if you want to do something like, if hovering over #divId increase x by one, and when you stop hovering decrease y by one:

    $("#divId").hover(function() { ++x; }, 
                      function() { --y; });
    

    If you really want an if hovering:

    var hovering = 0;
    $("#divId").hover(function() { hovering = 1; },
                      function() { hovering = 0; });
    ...
    // Then inside somewhere useful. Maybe in a setInterval, or triggered by
    //    another action...
    if (hovering) { ...
    

    Try it out with this jsFiddle

    For example:

    $(function() {
        var hovering = 0;
        $("div").hover(function() { hovering = 1; },
                       function() { hovering = 0; });
    
        $(document).keyup(function() {
             if (hovering) alert("hovering!");     // This is the "if hovering"
             else          alert("not hovering.");
        });
    });
    

提交回复
热议问题