如何在if语句jQuery中设置超时

时间:2018-09-17 12:18:26

标签: javascript jquery

无法弄清楚为什么在我将setTimeOut添加到if时为何不起作用, 我是在做错什么,还是如何在if语句中延迟执行?

if ($(window).scrollTop() > 1) {
    jQuery("html, body").animate({ scrollTop: $('#page-top-anchor').offset().top }, 1000);
    setTimeout(function() {
     jQuery('#'+$(this).data('modal')).fadeIn(1000); 
     jQuery('.a-modal').hide();       
    }, 1000);

在没有setTimeout的情况下,此代码可以正常工作,仅当我向其中添加setTimeout时,执行问题才会发生。

1 个答案:

答案 0 :(得分:1)

在这种情况下,您应该使用animate的完整回调,通过使用setTimeout,最终由于性能问题最终将失去与animate方法的同步。 http://api.jquery.com/animate/

if ($(window).scrollTop() > 1) {
jQuery("html, body").animate({ scrollTop: $('#page-top-anchor').offset().top }, 1000 , function() {
 // when animation completes
 jQuery('#'+$(this).data('modal')).fadeIn(1000); 
 jQuery('.a-modal').hide();       
});