running two jquery events at the same time causes

2019-09-07 03:02发布

问题:

I have two functions that I want to happen at the same time.

Function 1 is a window scrollTop and function2 is an absolute element hide (#elem1). These two functions take place immediately after an absolute element (#elem2) is placed on top of (#elem1).

Running these functions at the same time executes as:

elem1 scrolls top

elem1 is hidden

elem2 scrolls to top

This causes an instant flicker, blink on ios and I want to avoid it. I would have expected that changing the order of the functions would give me the results I expect, but it doesn't work (putting #elem1 hide before scrolltop).

How can I achieve this??

This is related to the following topic but I thought I would simplify it.

jquery element flicker after transition and scrolltop on ios

回答1:

Using the animate function (see: http://api.jquery.com/animate/) you can perform style updates only after previous animations have been completed. I'm sure there are other (prettier and more correct) ways of getting around it, but it seems to work.

$('#elem1').animate(
   { top: 0 }
   , {
       duration: 500
       , easing: "linear"
       , complete: function () {
           $('#elem1').animate(
               { opacity: 0 }
               , {
                   duration: 500
                   , complete: function () {
                       $('#elem2').animate(
                           { top: 0 }
                           , { duration:500 }
                       );
                   }
               }
           );
       }
   }
);