jQuery: implementare transizioni e trasformazioni CSS cross-browser

jQuery: implementare transizioni e trasformazioni CSS cross-browser

I browser complicano l'uso delle transizioni e trasformazioni CSS con l'uso dei prefissi. Fortunatamente esiste una soluzione.

La soluzione consiste nello stabilire quale proprietà CSS supporta il browser corrente (con prefisso o meno).


(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 ) { // Il primo valore supportato dal browser
					 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 )" );
	});
	
});

Demo e codice

jQuery: cross-browser CSS transitions and transformations

Torna su