Il metodo animate()
non supporta tutti i valori CSS forniti durante l'animazione. Ad esempio il valore auto
per le proprietà width
e height
non è supportato. Tuttavia possiamo ricorrere ad un semplice stratagemma per utilizzare anche questo valore. Vediamo come fare.
Possiamo clonare l'elemento da animare, rimuoverlo ed infine usare il clone per la nostra animazione:
(function($) {
$.fn.animateAuto = function(prop, speed, callback) {
var elem, height, width;
return this.each(function(i, el) {
el = $(el), elem = el.clone().css({
"height": "auto",
"width": "auto"
}).appendTo("body");
height = elem.css("height"), width = elem.css("width"), elem.remove();
if (prop === "height") {
el.animate({
"height": height
}, speed, callback);
}
else if (prop === "width") {
el.animate({
"width": width
}, speed, callback);
}
else if (prop === "both") {
el.animate({
"width": width,
"height": height
}, speed, callback);
}
});
}
})(jQuery);
Esempio:
$('#test').click(function() {
$(this).animateAuto('both', 1000);
});
Potete visionare l'esempio finale in questa pagina.