質問

Seems simple enough. I want an all <div>s to fadeOut() and then 1 of the <div>s to fadeIn(). But I get crazy behavior with something like this (jsfiddle with 3 <div>s)

<a href="#" onclick="$('div').fadeOut(2000, function() {$('div#first').fadeIn();}); return false;">Show first div</a>
<br/>
<a href="#" onclick="$('div').fadeOut(2000, function() {$('div#second').fadeIn();}); return false;">Show second div</a>
<br/>
<a href="#" onclick="$('div').fadeOut(2000, function() {$('div#third').fadeIn();}); return false;">Show third div</a>
<br/>
<div style="display:none" id="first">First div</div>
<div style="display:none" id="second">Second div</div>
<div style="display:none" id="third">Third div</div>

Sometimes the old div and the new div will disappear. Sometimes the new div will appear, fade and then reappear.

I think what's happening is when all divs fadeOut, each one of them calls the fadeIn function and that gets a little screwy. So what's a solution here to fadeIn only after all have been faded out?

役に立ちましたか?

解決

The problem is your callback gets called 3 times, one for each matched div after the animation for that div completes.

Here is an excerpt from the jQuery documentation:

Callback Function

If supplied, the callback is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but this is set to the DOM element being animated. If multiple elements are animated, it is important to note that the callback is executed once per matched element, not once for the animation as a whole.

As of jQuery 1.6, the .promise() method can be used in conjunction with the deferred.done() method to execute a single callback for the animation as a whole when all matching elements have completed their animations ( See the example for .promise() ).

here is a solution to your problem:

<a href="#" onclick="$('div').fadeOut(2000);$('div').promise().done(function() {$('div#first').fadeIn();}); return false;">Show first div</a>
<br/>
<a href="#" onclick="$('div').fadeOut(2000);$('div').promise().done(function() {$('div#second').fadeIn();}); return false;">Show second div</a>
<br/>
<a href="#" onclick="$('div').fadeOut(2000);$('div').promise().done(function() {$('div#third').fadeIn();}); return false;">Show third div</a>
<br/>
<div style="display:none" id="first">First div</div>
<div style="display:none" id="second">Second div</div>
<div style="display:none" id="third">Third div</div>
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top