Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

Callback of .animate() gets called twice jquery

Since I added some scrollTop-animation, some parts of my callback get called twice:

$('html, body').animate({scrollTop: '0px'}, 300,function() {
    $('#content').load(window.location.href, postdata, function() {                 
        $('#step2').addClass('stepactive').hide().fadeIn(700, function() {
            $('#content').show('slide',800);                    
        });
    });
});

It only seems to repeat the .show(), at least I don't have the impression that the load() or the .fadeIn() get called a second time too. The .show() gets repeated as soon as it has finished for the first time. Setting the scrollTop animation-speed to 0 didn't help by the way!

I assume it has something to do with the animation-queue, but I can't figure out how to find a workaround and especially why this is happening.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To get a single callback for the completion of multiple element animations, use deferred objects.

$(".myClass").animate({
  marginLeft: "30em"
}).promise().done(function(){
  alert("Done animating");
});

When you call .animate on a collection, each element in the collection is animated individually. When each one is done, the callback is called. This means if you animate eight elements, you'll get eight callbacks. The .promise().done(...) solution instead gives you a single callback when all animations on those eight elements are complete. This does have a side-effect in that if there are any other animations occurring on any of those eight elements the callback won't occur until those animations are done as well.

See the jQuery API for detailed description of the Promise and Deferred Objects.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...