JavaScript Small animation components and implementation Code _php Digest

Source: Internet
Author: User
Tags cos setinterval
Do a common animation effect, JS is how to complete it. Take a look at the example
Copy Code code as follows:

SetInterval (function () {
Element.style.left =parsefloat (element.style.left) + (n) + ' px ';
},10);

<div id= "test2" >test</div> <script> var element = document.getElementById ("Test2"); SetInterval (function () {Element.style.left =parsefloat (element.style.left) +2 + ' px '; },10);</script>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]

Use Window.setinterval animation function, every 10 milliseconds will go to perform an animation;
The Clearinterval function is matched with the set to end the animation.
Each setinterval will return a value similar to the thread ID;
var interval =setinterval (function () {
Element.style.left =parsefloat (element.style.left) + (n) + ' px ';
},10);
Use Clearinterval (interval) to end animation playback.
Interval = setinterval (function () {
if (parsefloat (element.style.left) >500) clearinterval (interval)
Element.style.left =parsefloat (element.style.left) +2 + ' px ';
},10);
More than 500px, the animation will stop and the element will not move.
<div id= "Test2" style= border:0px solid #00ff00;p osition:absolute;left:0px;top:400px;background: #0f0 ">test </div> <script> var element = document.getElementById (' test2 '); Interval = setinterval (function () {if (parsefloat (element.style.left) >500) clearinterval (interval) Element.style.left =parsefloat (element.style.left) +2 + ' px '; },10); </script>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]

But the above animation is more blunt, and then we have another timeline animation.
See Example:
var element = document.getElementById (' test1 ');
var start = +new Date,dur=1000,finish = Start+dur;
Interval = setinterval (function () {
var time = +new Date,
pos = time > Finish? 1: (Time-start)/dur;
Element.style.left = (100*pos) + "px";
if (time>finish) {
Clearinterval (interval);
}
},10);
Start is the starting time for the target animation (+new date is actually new date (). GetTime ())
Dur The total time required to perform the animation
Finish is the end of the target animation time
pos = time > Finish? 1: (Time-start)/dur; You can think of POS as frequency, one time than
(100*pos), 100 represents the distance, if the distance is 500px set to 500*pos;
Time>finish: If you exceed the time, stop the animation!
<div id= "Test2" style= border:0px solid #00ff00;p osition:absolute;left:0px;top:400px;background: #0f0 ">test </div> <script> var element = document.getElementById (' test2 '); var start = +new Date,dur=1000,finish = Start+dur; Interval = setinterval (function () {var time = +new Date, pos = time > Finish? 1: (Time-start)/dur; Element.style.left = (100*pos) + "px"; if (time>finish) {clearinterval (interval); }},10); </script>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]

Well, here we already know how a simple animation effect is written.
Let's look at how a small, complete animation component is written:
Copy Code code as follows:

(function ($,name) {
var parseel = document.createelement (' div ')
,
Props = (' backgroundcolor borderbottomcolor borderbottomwidth borderleftcolor ' +
' borderRightColor borderrightwidth borderspacing bordertopcolor bordertopwidth Bottom color fontsize ' +
' FontWeight height left letterspacing lineheight marginbottom marginleft marginright margintop ' +
' MaxWidth minheight minwidth opacity outlinecolor outlineoffset outlinewidth paddingbottom ' +
' Paddingright paddingtop right textindent top width wordspacing zindex '). Split (")
,
Normalize =function (style) {
var css,
Rules = {},
i = Props.length,
V
parseel.innerhtml = ' <div style= ' ' +style+ ' ></div> ';
CSS = Parseel.childnodes[0].style;
while (i--) if (v = css[props[i]]) rules[props[i] = Parse (v);
return rules;
},
color = function (Source,target,pos) {
var i = 2, J, C, tmp, V = [], r = [];
while (j=3,c=arguments[i-1],i--)
if (s (c,0) = = ' R ') {c = C.match (/\d+/g); while (j--) V.push (~~c[j]);} else {
if (c.length==4) c= ' # ' +s (c,1) +s (c,1) +s (c,2) +s (c,2) +s (c,3) +s (c,3);
while (j--) V.push (parseint (S (c,1+j*2,2), 16)); }
while (j--) {tmp = ~ ~ (v[j+3]+ (v[j]-v[j+3]) *pos); R.push (tmp<0?0:tmp>255?255:tmp);}
Return ' RGB (' +r.join ') + ') ';
},
Parse = function (prop) {
var p = parsefloat (prop), q = Prop.replace (/^[\-\d\.] +/,'');
Return isNaN (p)? {v:q, F:color, U: '}: {v:p, f:interpolate, u:q};
},
s = function (str, p, c) {
Return Str.substr (p,c| | 1);//color use
},
Interpolate =function (Source,target,pos) {
Return (source+ (Target-source) *pos). toFixed (3);
},
Flower = function (el, style,opts,after) {
var el = document.getElementById (EL),//Get element object by ID
opts = opts | | {},
target = normalize (style),
comp = El.currentstyle? El.currentStyle:getComputedStyle (EL, null),//ie and the consortium compatible, get the style
Prop
Current = {},
Start = +new date,//Start time
Dur = opts.duration| | 200,//execute event, default is 200
finish = Start+dur,//End time
Interval
easing = Opts.easing | | Function (POS) {return (-math.cos (POS*MATH.PI)/2) + 0.5;};
For (prop in target) current[prop] = Parse (comp[prop));
Interval = setinterval (function () {
var time = +new Date,
pos = time>finish? 1: (Time-start)/dur;
For (prop in target) {
El.style[prop] = TARGET[PROP].F (current[prop].v,target[prop].v,easing (POS)) + target[prop].u;
}
if (time>finish) {
Clearinterval (interval); Opts.after && Opts.after (); After && settimeout (after,1);
}
},10);
};
$[name] = flower;
}) (Window, "flower");

Copy Code code as follows:

var parse = function (prop) {
var p = parsefloat (prop), q = Prop.replace (/^[\-\d\.] +/,'');
Return isNaN (p)? {v:q, F:color, U: '}: {v:p, f:interpolate, u:q};
}
var p = parsefloat (prop) means: 500px => 500;
Q = Prop.replace (/^[\-\d\.] +/,''); 500px => px;
Return isNaN (p)? {v:q, F:color, U: '}: {v:p, f:interpolate, u:q}; If you take a color value (because it has a #), return {v:q, f:color, U: '} ' to represent you, F is a color function (which will be mentioned later);
var s = function (str, p, c) {return str.substr p,c| | 1); }

The S function is used to intercept the string and return the final result
The color function returns the "RGB (x,x,x)" form in the final uniform
The normalize function returns a JSON object that contains the name and value of the CSS property to be executed by the element
while (i--) if (v = css[props[i]]) rules[props[i] = Parse (v);
Take apart a line of code to see how it works
while (i--) {
Here A = number is used, first the assignment operation, if not exist if will not pass, kill two birds with one stone:
if (v = css[props[i]]) {
Rules[props[i]] = Parse (v); Assigned to a new object,
}
}
interpolate function return (source+ (Target-source) *pos). toFixed (3);
ToFixed is to solve decimal problems, such as 0.000000001; will become 1e-9; Not the results we want, through toFixed can be resolved, toFixed (n), where n represents the retention of the decimal point after several
El.currentstyle? El.currentStyle:getComputedStyle (EL, null);
This is actually compatible with multiple browsers, get the element of a code specific reference: JS get the final style "GetStyle"
Flower 4 Parameters El target object, style is the final style, opts, is the parameter options include (dur time, easing slow understand function, after the end of the operation of the Callbak), the 4th after is the final implementation of the Callbak;
Opts.easing can use various easing algorithms to change the motion state of elements;
Such as
Copy Code code as follows:

function Bounce (POS) {
if (Pos < (1/2.75)) {
return (7.5625*pos*pos);
else if (Pos < (2/2.75)) {
Return (7.5625* (pos-= (1.5/2.75)) *pos +. 75);
else if (Pos < (2.5/2.75)) {
Return (7.5625* (pos-= (2.25/2.75)) *pos +. 9375);
} else {
Return (7.5625* (pos-= (2.625/2.75)) *pos +. 984375);
}
}
(function ($,name) {
Window.flower = flower;
}) (window, ' flower ');

This actually allows the internal function to be free, and only exposes an interface through this call. Otherwise, the outside function cannot access the flower in the anonymous correspondence;
Look at the example of the call:
Copy Code code as follows:

<div id= "test1" style= "Position:absolute;left:0px;background: #f00; opacity:0" >test</div>
<div id= "Test2" style= border:0px solid #00ff00;p osition:absolute;left:0px;top:400px;background: #0f0 ">test </div>
<script>
(function ($,name) {
var parseel = document.createelement (' div ')
,
Props = (' backgroundcolor borderbottomcolor borderbottomwidth borderleftcolor ' +
' borderRightColor borderrightwidth borderspacing bordertopcolor bordertopwidth Bottom color fontsize ' +
' FontWeight height left letterspacing lineheight marginbottom marginleft marginright margintop ' +
' MaxWidth minheight minwidth opacity outlinecolor outlineoffset outlinewidth paddingbottom ' +
' Paddingright paddingtop right textindent top width wordspacing zindex '). Split (")
,
Normalize =function (style) {
var css,
Rules = {},
i = Props.length,
V
parseel.innerhtml = ' <div style= ' ' +style+ ' ></div> ';
CSS = Parseel.childnodes[0].style;
while (i--) if (v = css[props[i]]) rules[props[i] = Parse (v);
return rules;
},
color = function (Source,target,pos) {
var i = 2, J, C, tmp, V = [], r = [];
while (j=3,c=arguments[i-1],i--)
if (s (c,0) = = ' R ') {c = C.match (/\d+/g); while (j--) V.push (~~c[j]);} else {
if (c.length==4) c= ' # ' +s (c,1) +s (c,1) +s (c,2) +s (c,2) +s (c,3) +s (c,3);
while (j--) V.push (parseint (S (c,1+j*2,2), 16)); }
while (j--) {tmp = ~ ~ (v[j+3]+ (v[j]-v[j+3]) *pos); R.push (tmp<0?0:tmp>255?255:tmp);}
Return ' RGB (' +r.join ') + ') ';
},
Parse = function (prop) {
var p = parsefloat (prop), q = Prop.replace (/^[\-\d\.] +/,'');
Return isNaN (p)? {v:q, F:color, U: '}: {v:p, f:interpolate, u:q};
},
s = function (str, p, c) {
Return Str.substr (p,c| | 1);
},
Interpolate =function (Source,target,pos) {
Return (source+ (Target-source) *pos). toFixed (3);
},
Flower = function (el, style,opts,after) {
var el = document.getElementById (EL),
opts = opts | | {},
target = normalize (style),
comp = El.currentstyle? El.currentStyle:getComputedStyle (EL, null),
Prop
Current = {},
Start = +new Date,
Dur = opts.duration| | 200,
finish = Start+dur,
Interval
easing = Opts.easing | | Function (POS) {return (-math.cos (POS*MATH.PI)/2) + 0.5;};
For (prop in target) current[prop] = Parse (comp[prop));
Interval = setinterval (function () {
var time = +new Date,
pos = time>finish? 1: (Time-start)/dur;
For (prop in target) {
El.style[prop] = TARGET[PROP].F (current[prop].v,target[prop].v,easing (POS)) + target[prop].u;
}
if (time>finish) {
Clearinterval (interval); Opts.after && Opts.after (); After && settimeout (after,1);
}
},10);
};
$[name] = flower;
}) (Window, "flower");
(function () {
var bounce = function (pos) {
if (Pos < (1/2.75)) {
return (7.5625*pos*pos);
else if (Pos < (2/2.75)) {
Return (7.5625* (pos-= (1.5/2.75)) *pos +. 75);
else if (Pos < (2.5/2.75)) {
Return (7.5625* (pos-= (2.25/2.75)) *pos +. 9375);
} else {
Return (7.5625* (pos-= (2.625/2.75)) *pos +. 984375);
}
}
Flower (' test2 ', ' left:300px;padding:10px;border:50px solid #ff0000 ', {
DURATION:1500,
After:function () {
Flower (' test1 ', ' background: #0f0; Left:100px;padding-bottom:100px;opacity:1 ', {
duration:1234, Easing:bounce
});
}
});
})();
</script>

Reference: http://scripty2.com/doc/scripty2%20fx/s2/fx/transitions.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.