jQuery: animare la posizione di un'immagine di sfondo

Possiamo animare la posizione di un'immagine di sfondo con jQuery.

jQuery di Gabriele Romanato

Possiamo animare la posizione di un'immagine di sfondo con jQuery.

Creiamo il seguente plugin:


(function( $ ) {
	$.fn.animateBgPosition = function( x, y, speed ) {
    	var pos = this.css( "background-position" ).split( " " );


		this.x = parseInt( pos[0], 10 ) || 0;
		this.y = parseInt( pos[1], 10 ) || 0;

    	$.Animation( this, {
        	x: x,
					y: y
      	}, {
        	duration: speed
      	}).progress( function( e ) {
          	this.css( "background-position", e.tweens[0].now + "px " + e.tweens[1].now + "px" );
    	});

		return this;
	};
})( jQuery );

Esempio d'uso:


$(function() {
    $( "#bg" ).animateBgPosition( 100, 100, 1000 );
});

Commenti