2016-04-27 16 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