jquery 如何检查元素是否悬停

jquery how check an element has hover or not

我想检查一个元素的悬停状态,但是在这一行我收到一个错误:

if ($(this).nextAll('ul:first').is(':hover'))

这是错误:

Error: Syntax error, unrecognized expression: unsupported pseudo: hover

解决方法是什么?

  $(".sf-with-ul").hover(function() {
  $(this).nextAll('ul:first').css({
    "display": "block"
  });
  $(this).nextAll('ul:first').removeClass("fadeOutDownSmall");
  $(this).nextAll('ul:first').addClass("fadeInUpSmall");
}, function() {
  if ($(this).nextAll('ul:first').is(':hover')) {
    console.log('1');
  } else {
    console.log('2');
    $(this).nextAll('ul:first').css({
      "display": "none"
    });
    $(this).nextAll('ul:first').removeClass("fadeInUpSmall");
    $(this).nextAll('ul:first').addClass("fadeOutDownSmall");
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" data-ps2id-api="true" class="sf-with-ul"><span>Services</span></a>
<ul class="sub-menu animated fast fadeInUpSmall" style="display: block;">
  <li id="menu-item-1281" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1281"><a href="https://virtualvisacards.com/active-your-cards/" data-ps2id-api="true"><span>Activate Your Cards</span></a></li>
  <li id="menu-item-1271" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1271"><a href="https://virtualvisacards.com/card-balance/" data-ps2id-api="true"><span>Check Cards Balance</span></a></li>
</ul>

:hover 在保证金上被忽略。尝试将边距设置为 0。

.sf-with-ul + ul { margin: 0; }

注意: padding 将按预期工作

$(".sf-with-ul").hover(function() {
  $(this).nextAll('ul:first').css({
    "display": "block"
  });
  $(this).nextAll('ul:first').removeClass("fadeOutDownSmall");
  $(this).nextAll('ul:first').addClass("fadeInUpSmall");
}, function() {
  if ($(this).nextAll('ul:first').is(':hover')) {
    console.log('1');
  } else {
    console.log('2');
    $(this).nextAll('ul:first').css({
      "display": "none"
    });
    $(this).nextAll('ul:first').removeClass("fadeInUpSmall");
    $(this).nextAll('ul:first').addClass("fadeOutDownSmall");
  }
});
.sf-with-ul + ul {
  margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" data-ps2id-api="true" class="sf-with-ul"><span>Services</span></a>
<ul class="sub-menu animated fast fadeInUpSmall">
  <li id="menu-item-1281" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1281"><a href="https://virtualvisacards.com/active-your-cards/" data-ps2id-api="true"><span>Activate Your Cards</span></a></li>
  <li id="menu-item-1271" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1271"><a href="https://virtualvisacards.com/card-balance/" data-ps2id-api="true"><span>Check Cards Balance</span></a></li>
</ul>