Jquery condition check is(':hover') not working

后端 未结 8 1329
-上瘾入骨i
-上瘾入骨i 2020-11-28 15:15
$(\'.xx\').mouseenter(function(){
  if($(this).is(\':hover\'))
    alert(\'d\');
  else
     alert(\'f\');
});

Here is my code, it should alert \'d

相关标签:
8条回答
  • 2020-11-28 15:35

    Here is a little jQuery plugin that checks if the mouse is over an element.

    Usage:

    $("#YourElement").isMouseOverMe();

    Example:

    (function($) {
    
      var mx = 0;
      var my = 0;
    
      $(document).mousemove(function(e) { // no expensive logic here
        mx = e.clientX; 
        my = e.clientY;
      })
    
      $.fn.isMouseOverMe = function() {
    
        var $el = $(this);
        var el_xmin = $el.offset().left;
        var el_ymin = $el.offset().top;
        var el_xmax = el_xmin + $el.width();
        var el_ymax = el_ymin + $el.height();
        return mx >= el_xmin && mx <= el_xmax && my >= el_ymin && my <= el_ymax;
      };
    
    }(jQuery));
    
    $(document).mouseup(function(e) {
      console.log($("#div").isMouseOverMe())
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <h2>Click inside or outside of the yellow box</h2>
    <div id="div" style="width:200px;height:200px;background-color:yellow;margin-top:50px"></div>

    0 讨论(0)
  • 2020-11-28 15:43

    As Frederic said, :hover is part of CSS and is not a selector in jQuery.

    For an alternative solution, read How do I check if the mouse is over an element in jQuery?

    Set a timeout on the mouseout to fadeout and store the return value to data in the object. Then onmouseover, cancel the timeout if there is a value in the data.

    Remove the data on callback of the fadeout.

    0 讨论(0)
  • 2020-11-28 15:43

    Try something like this

    flag = ($('.xx:hover').length>0);
    

    So you can find out if the mouse is, the object

    0 讨论(0)
  • 2020-11-28 15:45

    Try something like this-

    $('.xx').hover(function(){        
            alert('d');
        }, function() {
           alert('f);
        });
    
    0 讨论(0)
  • 2020-11-28 15:46
    x.filter(':hover').length
    

    This may be also usable when you already had queried some objects / or inside callback function.

    0 讨论(0)
  • 2020-11-28 15:47

    :hover is a CSS pseudo-class, not a jQuery selector. It cannot be reliably used with is() on all browsers.

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