2016-04-27 72 views
0

我对JavaScript比较新。我最近在悬停时发现了这个switch div function。我也插入了下面的代码。我试图插入鼠标已从div中删除后发生的时间延迟。以便它不会立即变回原始文本。我会如何去做这件事?我想我需要使用setTimeOut(),但我还没有想出一个成功实现它的方法。JavaScript中的切换div功能的时间延迟

$('.switch').hover(function() { 
 
     $(this).find('.avg_words').hide(); 
 
     $(this).find('.avg_num').show(); 
 
    }, function() { 
 
     $(this).find('.avg_num').hide(); 
 
     $(this).find('.avg_words').show(); 
 
});
.avg_num { 
 
\t display: none; 
 
}
<div class="switch"> 
 
<div class="avg_words float_left"> 
 
    A+ (hover to see score) 
 
</div> 
 
<div class="avg_num"> 
 
    AVG = 98.35% 
 
</div> 
 
</div>

+1

'的setTimeout(函数(){/ *代码在这里* /},延迟);'或'...的setTimeout(functionName,而延迟);' – Jerry

回答

0

您可以使用setTimeout来运行延迟的功能。不要忘记存储这个时间间隔,这样您就不会在悬停时发生奇怪的抖动。

var i; 
$('.switch').hover(function() { 
     clearInterval(i); 
     $(this).find('.avg_words').hide(); 
     $(this).find('.avg_num').show(); 
    }, function() { 
     clearInterval(i); 
     i = setTimeout(function() { 
      $(this).find('.avg_num').hide(); 
      $(this).find('.avg_words').show(); 
     }.bind(this), 500); 
}); 
0

尝试使用setTimeout

$('.switch').hover(function() { 
    $(this).find('.avg_words').hide(); 
    $(this).find('.avg_num').show(); 
}, function() { 
    var _this = this; 
    setTimeout(function() { 
     $(_this).find('.avg_num').hide(); 
     $(_this).find('.avg_words').show(); 
    }, 1000); //delay in milliseconds, here 1s 
}); 

JSFiddle

+0

谢谢您的回答!我尝试过,但由于某些原因,它会卡在'avg_num'上,1秒后不会返回'avg_words'。 – Tobias

+0

对,我编辑了我的答案,现在应该可以工作。 – GAntoine

1

setTimeout这是超时对象的这一点。这就是为什么它不工作

$('.switch').hover(function() { 
     $(this).find('.avg_words').hide(); 
     $(this).find('.avg_num').show(); 
    }, function() { 
     var hoverObj = this; 
     setTimeout(function() { 
      $(hoverObj).find('.avg_num').hide(); 
      $(hoverObj).find('.avg_words').show(); 
     }, 1000); 
    }); 
+0

好的答案,只是一个提示:当想要保存对this的引用时,最好使用'_this'或'self'作为变量名称。 – GAntoine

+1

@ArcaneCraeda谢谢你的建议。下次我会记住这一点:)。 – MH09