【问题标题】:Mouse over event of jquery too fast鼠标悬停在 jquery 事件上太快
【发布时间】:2016-03-13 08:06:51
【问题描述】:

我必须在导航栏上显示一些东西(有 8 个项目)。

我在导航栏上使用了mouseover 来显示某组项目。问题是mouseover 太快了。有什么办法可以延迟这个事件吗?我只想在鼠标悬停时显示一些 div(带有数据)。

请注意,我想在鼠标悬停时显示我的 div,并在鼠标离开时隐藏我的 div。请建议我如何在某些鼠标事件中使用它?

我的示例代码: $(document).on('mouseover', '.menu', function(argument) { $(this).find('.drop-down').css('display', 'block'); }); $(document).on('mouseout', '.menu', function(argument) { $(this).find('.drop-down').css('display', 'none'); })

【问题讨论】:

  • 请发布一些代码来展示您的尝试。
  • 我可以使用其他功能来代替鼠标悬停和鼠标移出
  • 我的代码:$(document).on('mouseover', '.menu', function(argument) { $(this).find('.drop-down').css('显示', '块'); }); $(document).on('mouseout', '.menu', function(argument) { $(this).find('.drop-down').css('display', 'none'); }跨度>

标签: jquery mouseevent mouseover


【解决方案1】:

你可以使用 delay() 函数,它会帮助你得到想要的结果, 这是语法,

                    $(selector).delay(speed,queueName)

delay() 方法设置一个计时器来延迟队列中下一项的执行。

这里有一个很好的延迟函数示例 - jQuery delay() Method

【讨论】:

  • @user2814546,如果对您有帮助,请采纳答案!
【解决方案2】:

使用setTimeout 进行延迟(不仅适用于jquery,由于可能取消执行,它比delay 更好)。以下是菜单示例:

timer = setTimeout(function(){
    $this.find('.drop-down').show();
    timer = null;
    }, 400);

var timer;
var timerOut;

$(document).ready(function(){
  $('.menu').on('mouseover', function(){
    var $this = $(this);
    // clear existing timer to prevent showing another dropdown
    if(timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(function(){
      $this.find('.drop-down').show();
      timer = null;
    }, 400);
  });
  $('.menu').on('mouseout', function(){
    var $this = $(this);

    timerOut = setTimeout(function(){
      $this.find('.drop-down').hide();
      timer = null;
    }, 400);
  });
});
.menu{
  font-size:14px;
  background: lightgreen;
}
.drop-down{
  display:none;
  font-size:12px;
  padding-left:10px;
  background: lightblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="menu">
  <a>Menu1</a>
  <div class="drop-down">drop1.1</div>
  <div class="drop-down">drop2.1</div>
</div>
<div class="menu">
  <a>Menu2</a>
  <div class="drop-down">drop1.2</div>
  <div class="drop-down">drop2.2</div>
</div>

【讨论】:

  • 我使用过这样的函数: $(document).on('mouseover', '.menu', function(argument) { $(this).find('.drop-down' ).css('display', 'block'); }); $(document).on('mouseout', '.menu', function(argument) { $(this).find('.drop-down').css('display', 'none'); })
  • 你可能需要它不会隐藏,以防鼠标延迟返回,不是吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-12
  • 2011-11-09
相关资源
最近更新 更多