等到javascript函数完成后再执行更多操作

时间:2014-03-17 23:52:24

标签: javascript jquery html scroll

我有可扩展的标题,点击后显示内容。

我使用scrollTo方法滚动到当前单击的div,以确保它始终在屏幕视图中,而无需用户滚动。

然而,在我目前使用fadeIn / Out的地方看起来很乱,因为在页面滚动的同时项目正在淡入/淡出。

有什么方法我只能在scrollTo完成后淡出/淡出内容? e.g:

目前:

 $(document).on('click','.headingHelp',function(){
   $('html,body').animate({ scrollTop: $(this).offset().top }, 'slow');
   $('.infoHelp').fadeOut();
   $('.headingHelp_sel').attr('class', 'headingHelp');
   $(this).next('.infoHelp').fadeIn();
   $(this).attr('class', 'headingHelp_sel');
 });

然而我想要的是:

 function scrollToDiv() {
   $('html,body').animate({ scrollTop: $(this).offset().top }, 'slow');
 }

 $(document).on('click','.headingHelp',function(){
   scrollToDiv() {
     // ONLY DO THIS ONCE FINISHED SCROLLING
     $('.infoHelp').fadeOut();
     $('.headingHelp_sel').attr('class', 'headingHelp');
     $(this).next('.infoHelp').fadeIn();
     $(this).attr('class', 'headingHelp_sel');
   }
 });

2 个答案:

答案 0 :(得分:1)

您可以使用回调:

$('html,body').animate({scrollTop: $(this).offset().top},'slow',function(){
    //all the code you want to execute later goes here
});

答案 1 :(得分:0)

如果我没记错的话,你可以使用动画promise

function scrollToDiv() {
    return $('html,body')
               .animate({ scrollTop: $(this).offset().top }, 'slow').promise();
}

像这样使用:

scrollToDiv().done(function(){
    $('.infoHelp').fadeOut();
    $('.headingHelp_sel').attr('class', 'headingHelp');
    $(this).next('.infoHelp').fadeIn();
    $(this).attr('class', 'headingHelp_sel');
});