开发者

jQuery fadeOut/fadeIn not working as expected?

I'm trying to show one fieldset at a time, based on the user's selection. The theory is that, all fieldsets should hide first, then the selected fieldset should be shown. I'm using jQuery's fadeOut and 'fadeIn` functions开发者_高级运维.

You can see a fiddle of this here.

But it doesn't work just fine. What's wrong? When you change the ownership type, first two fieldsets are shown, then they dim and fade out, and then the intended fieldset appears. However, the desired behavior is that, on change of the ownership type, the currently visible fieldset simply fade out, and then the intended fieldset fade in.


You can also use a 'promise' http://api.jquery.com/jQuery.when/ to be sure that fadein happens after when fieldset has faded out.

$(function() {
    var ownershipType = $('#ownershipType').first();
    var fieldsets = $('fieldset');
    ownershipType.change(function() {
        var promise = fieldsets.fadeOut(2000);
        $.when(promise).then( function () {$('fieldset[data-ownership-type=' + ownershipType.val() + ']').fadeIn('fast');
        });
    });
});

http://jsfiddle.net/DtaHQ/26/


The problem is that you already have hidden fieldset and for these elements animation of the fadeOut fires immediately, because of it's already hidden.

Try to change to this:

$(function() {
    var ownershipType = $('#ownershipType').first();
    ownershipType.change(function() {
        $('fieldset:visible').fadeOut(2000, function() {
            $('fieldset[data-ownership-type=' + ownershipType.val() + ']').fadeIn('fast');
        });
    });
});

Code: http://jsfiddle.net/DtaHQ/20/


Change your code to

$(function() {
    var ownershipType = $('#ownershipType').first();
    var fieldsets = $('fieldset');
    ownershipType.change(function() {
        $('fieldset:visible').fadeOut(2000, function() {
            $('fieldset[data-ownership-type=' + ownershipType.val() + ']').fadeIn('fast');
        });
    });
});

You only want to fade out the fieldset that is currently visible.

http://jsfiddle.net/DtaHQ/24/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜