对于那些寻找更短但有效的版本的人,您可以这样做:
$('a#trigger').on('click', function(e) {
e.preventDefault();
var w = ($('div#test').width() == 300 ? 100 : 300);
$('div#test').animate({width:w},150);
});
最短的版本:
$('a#trigger').on('click', function(e) {
e.preventDefault();
$('div#test').animate({width:($('div#test').width() == 300 ? 100 : 300)},150);
});
关于函数:
function toggleWidth(target, start, end, duration) {
var w = ($(target).width() == start ? end : start);
$(target).animate({width:w},duration);
return w;
}
用法:
$('a#trigger').on('click', function(e) {
e.preventDefault();
toggleWidth($("div#test"), 300, 100, 150);
});
终于有了一个 JQuery.fn.extend 函数:
jQuery.fn.extend({
toggleWidth: function(start, end, duration) {
var w = ($(this).width() == start ? end : start);
$(this).animate({width:w},duration);
return w;
}
});
用法:
$('a#trigger').on('click', function(e) {
e.preventDefault();
$("div#test").toggleWidth(300, 100, 150);
});