【问题标题】:Jquery: Why isn't timer being cancelled on mouseleave?Jquery:为什么没有在鼠标离开时取消计时器?
【发布时间】:2015-05-08 15:05:08
【问题描述】:

我编写了一些代码,用于在鼠标进入 div 时延迟后触发 jquery 事件,但如果鼠标在延迟期间离开 div 则取消。该代码运行良好,但我尝试将相同的代码格式应用于另一个 jquery 事件,如果我的鼠标在延迟期间离开 div,该事件不会取消。这是我的新代码不起作用:

<div class="expander"><%=image_tag("BigCircle2.jpg")%></div>
<script type="text/javascript">
  $(".expander").on('mouseenter', function () {
    $.data(".expander", 'timer', setTimeout(function() {
      $(".expander").stop(true, true).animate({width: "150%"}, 270, function() {
      });
    }, 400));
  }).on('mouseleave', function() {
    clearTimeout($.data(".expander", 'timer'));
    $(".expander").stop(true, true).animate({width: "100%"}, 270, function() {
    });
  });
  $(".expander").mouseleave(function () {
    $(".expander").animate({width: "100%"}, 270, function() {
    });
  });
</script>

问题是,如果鼠标在 400 延迟期间离开 .expander,则不会取消 mouseenter 事件。有人看到我的代码有什么问题吗?


这是我完美执行的初始代码:

<script type="text/javascript">
  $("#top").hide();
  $("#con").on('mouseenter', function () {
    $.data(this, 'timer', setTimeout(function() {
      $('#top').stop(true, true).fadeIn("fast");
    }, 400));
  }).on('mouseleave', function() {
    clearTimeout($.data(this, 'timer'));
    $('#top').stop(true, true).fadeOut('fast');
  });
  $("#con").mouseleave(function () {
    $('#top').fadeOut("fast");
  });
</script>

【问题讨论】:

  • 为什么要删除this?它是您所有数据的上下文。
  • 使用this 会导致上下文丢失。使用this,jquery 事件根本没有被触发:stackoverflow.com/questions/28892531/error-in-jquery-syntax
  • 我更新了我的答案以避免完全使用this。为什么代码没有包含在文档就绪函数中?

标签: javascript jquery timer timeout


【解决方案1】:

jQuery 的$.data() 需要一个 DOM 对象...新代码使用的是字符串选择器。

$.data(".expander")

将其更改为 this 或不要使用 $.data()

更新:“不要使用$.data()”我的意思是:

var timer;
$(".expander").on('mouseenter', function () {
    timer = setTimeout(function() {
        $(".expander").stop(true, true).animate({width: "150%"}, 270, function() {
        });
    }, 400);
}).on('mouseleave', function() {
    clearTimeout(timer);
    $(".expander").stop(true, true).animate({width: "100%"}, 270, function() {});
});
$(".expander").mouseleave(function () {
    $(".expander").animate({width: "100%"}, 270, function() {});
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    • 1970-01-01
    • 1970-01-01
    • 2012-06-15
    • 1970-01-01
    相关资源
    最近更新 更多