jQuery 延迟问题

标签 jquery delay

<script type="text/javascript">
 $(document).ready(function() {
  $(".module .caption").hide();
  $(".module").hover(function() {
     $(this).find(".caption").slideDown().end().siblings('.module').addClass('under');
   },function() {
     $(this).find(".caption").slideUp().end().siblings('.module').removeClass('under').delay(10000);   
   });
 });
</script>

这很好用,除了 .delay 不起作用,我的语法错误吗?我只是想在鼠标悬停时将 .removeClass("under") 延迟一两秒。我不想延迟滑动。

有什么想法吗?

最佳答案

delay() 默认作用于 fx 队列。 removeClass 不会添加到任何队列,因此在不进行一些更改的情况下不会受到 delay() 的影响。

您可以:

  1. 手动将 removeClass 调用添加到 fx 队列
  2. 改用setTimeout

解决方案1 ​​请注意 jQuery 链中 delay 的重新排列!:

$(this).find(".caption").slideUp().end().siblings('.module').delay(1000).queue(function () {
    $(this).removeClass('under').dequeue(); // dequeue is IMPORTANT!
});

解决方案2:

  $(".module").hover(function() {
     $(this).find(".caption").slideDown().end().siblings('.module').addClass('under');
   },function() {
     var self = $(this).find(".caption").slideUp().end().siblings('.module');

     setTimeout(function () {
        self.removeClass('under');
     }, 1000);   
   });

请注意,如果有人将鼠标悬停/移出几次,这两种解决方案都会产生奇怪(但不同)的效果。要解决 #1 的问题,请在鼠标悬停时将 .stop().clearQueue() 添加到链中。要解决问题#2,请存储对超时的引用,并在鼠标悬停时clearTimeout(theVariable)

关于jQuery 延迟问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2982824/

相关文章:

jquery - 如何替换表列值

javascript - jQuery - 网格返回不均匀的行和列

javascript - 从 WEB 拉取 JSON 时出现内存泄漏

java - Java Swing Timer 的随机时间间隔?

php echo 语句如果屏幕是一定大小

javascript - 每个定义的时间延迟关键帧并在动画后保持不透明度为 0

ruby-on-rails - 启动同一作业的多个延迟作业进程

javascript - (游戏编程)如何在攻击之间添加延迟?

javascript - 在循环的javascript迭代之间应用延迟

jquery - 我需要分割每两个 li 并将它们附加到 div