【发布时间】: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