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

前端 未结 5 1042
离开以前
离开以前 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:14
    .is(':hover');
    

    or

    $('#divId:hover');
    
    0 讨论(0)
  • 2021-02-18 18:24

    You can use .hover(). It's can be used like so:

    $("selector").hover(
        function (){
            //mouse over
        },
        function (){
           //mouse out
        }
    );
    

    An example of it's use from the documentation is here:

    $("li").hover(
      function () {
        $(this).append($("<span> ***</span>"));
      }, 
      function () {
        $(this).find("span:last").remove();
      }
    );
    
    0 讨论(0)
  • 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.");
        });
    });
    
    0 讨论(0)
  • 2021-02-18 18:27

    Updated answer!

    $("#foo").hover(function() {
        $(this).data("hovered", true);
    }, function() {
        $(this).data("hovered", false);
    }); 
    

    Testing if it is hovered...

    if ( $("#foo").data("hovered") ) {
        // it is hovered
    } else {
        // it's not hovered
    }
    
    0 讨论(0)
  • 2021-02-18 18:30

    Depending on what you are doing either mouseover() (http://api.jquery.com/mouseover/) or hover() (http://api.jquery.com/hover/) can be useful.

    0 讨论(0)
提交回复
热议问题