Jquery: 为什么在 mouseleave 时不取消计时器?

Jquery: Why isn't timer being cancelled on mouseleave?

我为 jquery 事件编写了一些代码,当鼠标输入 div 时延迟后触发,但如果鼠标在延迟期间离开 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>

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

$.data(".expander")

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

更新:"don't use $.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() {});
});