【问题标题】:Best practice for executing code on mouseover (or mouseout) only仅在鼠标悬停(或鼠标悬停)时执行代码的最佳实践
【发布时间】:2017-09-05 18:01:55
【问题描述】:

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

$('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 部分会一直触发,而不是触发一次。

有什么建议吗?

【问题讨论】:

  • 使用标志并在第一次触发后将其设置为 false。
  • 当悬停任何 li 元素时,我会显示一个背景图像(与每个 li 元素相关联)。当悬停在整个列表之外时,我想切换回默认背景图像。在 li 元素之间悬停时,我不想切换到默认图像。

标签: jquery hover mouseover mouseout


【解决方案1】:

当我将指针移到元素上时,鼠标悬停部分会持续触发, 而不是一次发射。

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

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>

【讨论】:

    【解决方案2】:

    向您输入的li 添加一个活动类....离开ul 时删除所有活动类

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

    【讨论】:

      【解决方案3】:

      您可能想要使用event delegation

      这样的事情应该可以工作:

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

      【讨论】:

        【解决方案4】:

        你可以使用https://api.jquery.com/mouseenter/ mouseenter 代替 mouseover

        【讨论】:

          猜你喜欢
          • 2023-03-07
          • 1970-01-01
          • 2011-08-04
          • 2018-09-03
          • 2015-09-03
          • 1970-01-01
          • 2015-04-22
          • 2011-05-26
          • 2017-10-14
          相关资源
          最近更新 更多