仅在鼠标悬停(或鼠标移出)时执行代码的最佳实践

Best practice for executing code on mouseover (or mouseout) only

我想在悬停元素时执行代码。当指针消失时,我不想发生任何事情。这段代码完全符合我的要求:

$('li').hover(function() {
  // actions here
},
function() {
});

$('ul').hover(function() {
},
function() {
  // other actions here
});

但是很丑。我期待这个更干净的版本可以工作:

$('li').mouseover(function() {
  // actions here
});

$('ul').mouseout(function() {
  // other actions here
});

但事实并非如此。 mouseover 部分在我将指针移到元素上时一直触发,而不是触发一次。

有什么建议吗?

你可以使用 https://api.jquery.com/mouseenter/ mouseenter 而不是 mouseover

您可能想要使用 event delegation

像这样的东西应该可以工作:

$('ul').on('mouseover', 'li', function() { console.log('hovered'); });

The mouseover part keeps firing as I move my pointer over the element, rather than firing once.

您可以使用标志仅执行一次代码块,但是,这不会阻止事件多次重新触发,它只会忽略第一个事件之后的事件。

var flag = true;
$('li').mouseover(function() {
   if(flag){

   // actions here
    flag = false;
   }
});

不过,我建议查看 .mouseenter()

片段

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js">
    </script>
  </head>
  <body>
    <ul>
      <li>list item</li>
      <li>list item</li>
      <li>list item</li>
      <li>list item</li>
      <li>list item</li>
    </ul>

    <script>
      var flag = true;
      $('li').mouseover(function() {
        if(flag){
          console.log("testing");
          // actions here
          flag = false;
        }
     });

    $('ul').mouseout(function() {
     // other actions here
    });

   </script>
 </body>
</html>

添加一个活跃的 class 到 li 你输入....删除所有活跃的 classes 离开时 ul

$('li').mouseenter(function(){
  $(this).addClass('active');
});

$('ul').mouseleave(function(){
  $(this).find('.active').removeClass('active');
})