我有这样的脚本
$('.parent a').live('mouseover mouseout', function(event) {
if (event.type == 'mouseover'){
if ($(this).siblings('.child').css('width') == '0px' ){
$(this).siblings('.child').animate({'width': window.innerWidth}, 500);
}
}else{
if ( !$(this).hasClass('active') ){
$(this).siblings('.child').animate({'width': 0}, 500);
}
}
});
正如您从上面的脚本中注意到的那样,如果我们将鼠标移到
$('.parent a')
上,则它的兄弟姐妹将扩展其宽度。现在,如果我们将鼠标移到上方,它的兄弟姐妹会立即爆发,我想在
5 seconds
之后将鼠标移到上方时使其发生怎么做?
最佳答案
请注意,我添加了单独的事件侦听器,而不是在事件处理程序中针对不同的事件类型进行测试。
var timer;
$('.parent a').live('mouseover', function(event) {
$Sibling = $(this).siblings(".child");
timer = window.setTimeout(function() {
if ($Sibling.css('width') == '0px' ){
$Sibling.animate({'width': window.innerWidth+"px"}, 500);
}}, 5000);
});
$('.parent a').live('mouseout', function(event) {
if (timer) {
window.clearTimeout(timer);
}
if ( !$(this).hasClass('active') ){
$(this).siblings('.child').animate({'width': "0px"}, 500);
}
});
其背后的想法是,您将计时器设置为在用户将鼠标悬停在锚点上时运行。如果它们在计时器触发之前移出鼠标,则清除计时器以停止事件的发生。否则,当计时器触发时,它将按照原始脚本扩展该元素。
另外,通过让jQuery仅遍历DOM一次并将结果存储在$ Sibling中,我们可以使脚本更快。
为了测试这一点,我使用了以下HTML。
<div class="parent">
<a href="#">Hello</a>
<div class="child" style="background-color: Aqua; display: block; width: 0px; overflow: hidden;">World</div>
</div>