jQuery può essere un valido aiuto per gestire le transizioni e trasformazioni CSS.
Possiamo implementare il seguente oggetto di utility che verrà poi usato da due plugin specifici:
(function( $ ) {
var CSS = {} || Object.create( null );
CSS.fn = {
properties: {
transform: [ "transform", "msTransform", "webkitTransform", "mozTransform", "oTransform" ],
transition: [ "transition", "msTransition", "webkitTransition", "mozTransition", "oTransition" ]
},
_getSupportedProperty: function( props ) {
var root = document.documentElement;
for ( var i = 0; i < props.length; ++i ) {
var prop = props[i];
if ( prop in root.style ) {
return prop;
}
}
},
transform: function( element, value ) {
var self = this;
var prop = self._getSupportedProperty( self.properties.transform );
element.style[prop] = value;
},
transition: function( element, value ) {
var self = this;
var prop = self._getSupportedProperty( self.properties.transition );
element.style[prop] = value;
}
};
$.fn.transition = function( value ) {
return this.each(function() {
var element = this;
CSS.fn.transition( element, value );
});
};
$.fn.transform = function( value ) {
return this.each(function() {
var element = this;
CSS.fn.transform( element, value );
});
};
})( jQuery );
Esempio d'uso:
$(function() {
var $test = $( "#test" );
$test.transition( "all 500ms ease-out" );
$test.click(function() {
$( this ).transform( "translate( 20px,20px )" );
});
});