When creating animated effects on Web pages, sometimes you want to insert a picture through the background, and then control the position of the background display to achieve some animation effects, so that you do not use absolute positioning control left and top to achieve animation effect! But the animation function of jquery itself does not support background animation! Here we introduce an animated plugin to achieve the effect of background animation!
The code is as follows! (jqbackgroundpositionanimate.js)
/*Revision for the advanced version of JQuery. weibo.com/61557518*/(function($) { if(!document.defaultview | |!document.defaultView.getComputedStyle) {varOldcurcss =$.curcss; $.curcss=function(Elem, name, force) {if(name = = = ' Background-position ')) {Name= ' backgroundposition '; } if(Name!== ' backgroundposition ' | |!elem.currentstyle | |Elem.currentstyle[name]) { returnOldcurcss.apply ( This, arguments); } varstyle =Elem.style; if(!force && Style &&Style[name]) { returnStyle[name]; } returnOldcurcss (Elem, ' backgroundPositionX ', force) + ' + oldcurcss (elem, ' backgroundpositiony '), force); }; } varOldanim =$.fn.animate; $.fn.animate=function(prop) {if(' Background-position 'inchprop) {prop.backgroundposition= prop[' Background-position ']; Deleteprop[' Background-position ']; } if(' backgroundposition 'inchprop) {prop.backgroundposition= ' (' +prop.backgroundposition; } returnOldanim.apply ( This, arguments); }; functionToArray (STRG) {STRG= Strg.replace (/left|top/g, ' 0px ')); STRG= Strg.replace (/right|bottom/g, ' 100% ')); STRG= Strg.replace (/([0-9\.] +) (\s|\) |$)/g, "$1px$2"); varres = Strg.match (/(-?[ 0-9\.] +) (px|\%|em|pt) \s (-?[ 0-9\.] +) (PX|\%|EM|PT)/); return[Parsefloat (Res[1], ten), Res[2], parsefloat (Res[3], ten), res[4]]; } $.fx.step.backgroundposition=function(FX) {if(!fx.bgposready) {varStart = $.css (Fx.elem, ' backgroundposition ')); if(!start) {Start= ' 0px 0px '; } Start=ToArray (start); Fx.start= [Start[0], start[2]]; varEnd =ToArray (fx.end); Fx.end= [End[0], end[2]]; Fx.unit= [End[1], end[3]]; Fx.bgposready=true; } varNOWPOSX = []; nowposx[0] = ((Fx.end[0]-fx.start[0]) * Fx.pos) + fx.start[0] + fx.unit[0]; nowposx[1] = ((fx.end[1]-fx.start[1]) * Fx.pos) + fx.start[1] + fx.unit[1]; Fx.elem.style.backgroundPosition= Nowposx[0] + "+ nowposx[1]; };}) (jQuery);
The above code is an extension of jquery, so introduce jquery! before use
Here's how to use it:
$ ("#select"). Animate ({backgroundposition: ' (0 0) '}, {duration:300,function () {
/*
Script to end execution of animation
*/
});
$ ("#select"). Animate ({backgroundposition: ' (left-873px) '}, {duration:300})
Duration speed (per millisecond)
This plugin compatibility is still possible, support IE6, and other mainstream browser, the effect is good! The key is to save a lot of time to write the structure, direct use of background positioning to replace!
jquery Background Animation plugin uses