基于布尔值的fadeIn / fadeOut
我想知道我是否真的要写:
if (status) { $('#status-image-' + id).fadeIn(); } else { $('#status-image-' + id).fadeOut(); }
或者有一个函数,我可以提供我的布尔状态,如:
$('#status-image-' + id).fade(status);
我见过fadeToggle,但它不接受布尔状态参数。
不,没有,但你可以做一个这样的:
jQuery.fn.fadeInOrOut = function(status){ return status ? this.fadeIn() : this.fadeOut(); }
然后像那样调用它(请参阅此jsfiddle以获取certificate):
$('#status-image-' + id).fadeInOrOut(status);
这是你想要的吗?
我知道写这篇文章的最短路,但我觉得个人可憎的是:
$('#status-image-' + id)[status ? 'fadeIn' : 'fadeOut']();
您当然可以直接将建议的函数添加到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);
这是未经测试的 – 我只是当场敲了它。
提供的第一个参数将是您的status
参数 – 其余参数将传递给.fadeIn()
或.fadeOut()
。