最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - fadeInfadeOut based on a boolean - Stack Overflow

programmeradmin1浏览0评论

I was wondering if I really have to write:

if (status) {
    $('#status-image-' + id).fadeIn();
} else {
    $('#status-image-' + id).fadeOut();
}

or there is a function to which I can provide my boolean status, something like:

$('#status-image-' + id).fade(status);

I've seen fadeToggle, but it doesn't accept a boolean status parameter.

I was wondering if I really have to write:

if (status) {
    $('#status-image-' + id).fadeIn();
} else {
    $('#status-image-' + id).fadeOut();
}

or there is a function to which I can provide my boolean status, something like:

$('#status-image-' + id).fade(status);

I've seen fadeToggle, but it doesn't accept a boolean status parameter.

Share Improve this question asked Nov 11, 2011 at 8:47 stivlostivlo 85.5k35 gold badges147 silver badges200 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 17

No, there is not, but you can make one like that:

jQuery.fn.fadeInOrOut = function(status){
    return status ? this.fadeIn() : this.fadeOut();
}

and then call it like that (see this jsfiddle for a proof):

$('#status-image-' + id).fadeInOrOut(status);

Is it what you wanted?

The shortest way I know of to write this, but one I find personally abhorrent, is this:

$('#status-image-' + id)[status ? 'fadeIn' : 'fadeOut']();

You can of course just add the proposed function straight to jQuery:

(function($) {
    $.fn.fade = function() {
        var args = Array.prototype.slice.call(arguments);  
        var status = args.shift();
        var func = status ? 'fadeIn' : 'fadeOut';
        return $.fn[func].apply(this, args);
    };
})(jQuery);

This is untested - I just knocked it up on the spot.

The first argument supplied will be your status parameter - the remaining arguments will be passed through to .fadeIn() or .fadeOut().

发布评论

评论列表(0)

  1. 暂无评论