Home  >  Article  >  Backend Development  >  JavaScript small animation components and implementation code_PHP tutorial

JavaScript small animation components and implementation code_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:36:51724browse

How to create a common animation effect using js? Take a look at the example

Copy the code The code is as follows:

setInterval (function(){
element.style.left =parseFloat(element.style.left) +(n) +'px';
},10);


[Ctrl+A to select all Note: If you need to introduce external Js, you need to refresh to execute]

Use window.setInterval animation function, every 10 milliseconds The animation will be executed once;
and set are matched with the clearInterval function, which is used to end the animation.
Every 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);
When it exceeds 500px, the animation will will stop and the element will no longer move.

[Ctrl+A Select all Note: If you need to introduce external Js, you need to refresh to execute]

But the above animation is relatively stiff, and then we There is another kind of timeline animation.
Look at the 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 start time of the target animation ( +new Date is actually new Date( ).getTime() )
dur is the total time required for animation execution
finish is the end time of the target animation
pos = time > finish ? 1 : (time-start)/dur; // You can think of pos as frequency, a time ratio
(100*pos), 100 represents the distance, if the distance is 500px, set it to 500*pos;
time>finish: If it exceeds the time, stop the animation!

[Ctrl+A to select all Note: If you need to introduce external Js, you need to refresh to execute]

Very good, we already know a simple animation here How to write the effect.
Let’s look at how to write a small complete animation component:
Copy the code The code is as follows:

(function($,name){
var parseEl = document.createElement('div')
,
props = ('backgroundColor borderBottomColor borderBottomWidth borderLeftColor borderLeftWidth '+
'borderRightColor borderRightWidth borderSpacing borderTopColor borderTopWidth bottom color fontSize '+
'fontWeight height left letterSpacing lineHeight marginBottom marginLeft marginRight marginTop maxHeight '+
'maxWidth minHeight minWidth opacity outlineColor outlineOffset outlineWidth paddingBottom paddingLeft '+
'paddingRight paddingTop right textIndent top width wordSpacing zIndex').split(' ')
,
normalize =function (style){
var css,
rules = {},
i = props.length,
v;
parseEl.innerHTML = '
';
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 用
},
interpolate =function(source,target,pos){
return (source+(target-source)*pos).toFixed(3);
},
flower = function(el, style,opts,after){
var el = document.getElementById(el), //通过id获取元素对象
opts = opts || {},
target = normalize(style),
comp = el.currentStyle ? el.currentStyle : getComputedStyle(el, null), //ie和w3c兼容,获取样式
prop,
current = {},
start = +new Date, //开始时间
dur = opts.duration||200, //执行事件,默认为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");

复制代码 代码如下:

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) 意思是 : 500px => 500;
q = prop.replace(/^[-d.]+/,''); 500px => px;
return isNaN(p) ? { v: q, f: color, u: ''} : { v: p, f: interpolate, u: q }; 意思是 如果取的是颜色值(因为带有#号),返回{ v: q, f: color, u: ''} u 代表代为,f是一个color函数(后面会讲到);
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 uniformly returns the color value in the form of "rgb(x,x,x)". The
normalize function returns a json object. , the object contains the name and value of the css attribute to be executed by the element
while(i--) if(v = css[props[i]]) rules[props[i]] = parse(v);
Tear apart a line of code and see how it works
while(i--){
//A = sign is used here, and the assignment operation is performed first. If it does not exist, the if will not pass, killing two birds with one stone: )
if(v = css[props[i]]){
rules[props[i]] = parse(v); //Assign to new object,
}
}
In the interpolate function, return (source+(target-source)*pos).toFixed(3);
toFixed is to solve the decimal problem, such as 0.000000001; will become 1e-9; which is not the result we want, pass toFixed can be solved, toFixed (n), where n represents the number of decimal places to retain
el.currentStyle? el.currentStyle: getComputedStyle(el, null);
This is actually compatible with multiple browsers, one line of code to get the element Specific reference: JS gets the final style [getStyle]
Flower’s 4 parameters el target object, style is the final style, opts, is the parameter options including (dur time, easing function, callbak run after the end), The fourth after is the last callbak executed;
opts.easing can use various easing algorithms to change the motion state of elements;
such as
Copy code The code is 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 makes the internal function free and exposes an interface only through this call. Otherwise, external functions cannot access the flower in anonymous correspondence;
Look at the calling example : )
Copy the code The code is as follows:

test

test

<script> <br>(function($,name){ <br>var parseEl = document.createElement('div') <br>, <br>props = ('backgroundColor borderBottomColor borderBottomWidth borderLeftColor borderLeftWidth '+ <br>'borderRightColor borderRightWidth borderSpacing borderTopColor borderTopWidth bottom color fontSize '+ <br>'fontWeight height left letterSpacing lineHeight marginBottom marginLeft marginRight marginTop maxHeight '+ <br>'maxWidth minHeight minWidth opacity outlineColor outlineOffset outlineWidth paddingBottom paddingLeft '+ <br>'paddingRight paddingTop right textIndent top width wordSpacing zIndex').split(' ') <br>, <br>normalize =function (style){ <br>var css, <br>rules = {}, <br>i = props.length, <br>v; <br>parseEl.innerHTML = '<div style="'+style+'"></div>'; <br>css = parseEl.childNodes[0].style; <br>while(i--) if(v = css[props[i]]) rules[props[i]] = parse(v); <br>return rules; <br>}, <br>color = function(source,target,pos){ <br>var i = 2, j, c, tmp, v = [], r = []; <br>while(j=3,c=arguments[i-1],i--) <br>if(s(c,0)=='r') { c = c.match(/d+/g); while(j--) v.push(~~c[j]); } else { <br>if(c.length==4) c='#'+s(c,1)+s(c,1)+s(c,2)+s(c,2)+s(c,3)+s(c,3); <br>while(j--) v.push(parseInt(s(c,1+j*2,2), 16)); } <br>while(j--) { tmp = ~~(v[j+3]+(v[j]-v[j+3])*pos); r.push(tmp<0?0:tmp>255?255:tmp); } <br>return 'rgb('+r.join(',')+')'; <br>}, <br>parse = function(prop){ <br>var p = parseFloat(prop), q = prop.replace(/^[-d.]+/,''); <br>return isNaN(p) ? { v: q, f: color, u: ''} : { v: p, f: interpolate, u: q }; <br>}, <br>s = function(str, p, c){ <br>return str.substr(p,c||1); <br>}, <br>interpolate =function(source,target,pos){ <br>return (source+(target-source)*pos).toFixed(3); <br>}, <br>flower = function(el, style,opts,after){ <br>var el = document.getElementById(el), <br>opts = opts || {}, <br>target = normalize(style), <br>comp = el.currentStyle ? el.currentStyle : getComputedStyle(el, null), <br>prop, <br>current = {}, <br>start = +new Date, <br>dur = opts.duration||200, <br>finish = start+dur, <br>interval, <br>easing = opts.easing || function(pos){ return (-Math.cos(pos*Math.PI)/2) + 0.5; }; <br>for(prop in target) current[prop] = parse(comp[prop]); <br>interval = setInterval(function(){ <br>var time = +new Date, <br>pos = time>finish ? 1 : (time-start)/dur; <br>for(prop in target){ <br>el.style[prop] = target[prop].f(current[prop].v,target[prop].v,easing(pos)) + target[prop].u; <br>} <br>if(time>finish) { <br>clearInterval(interval); opts.after && opts.after(); after && setTimeout(after,1); <br>} <br>},10); <br>}; <br>$[name] = flower; <br>})(window,"flower"); <br>(function(){ <br>var bounce = function(pos) { <br>if (pos < (1/2.75)) { <BR>return (7.5625*pos*pos); <BR>} else if (pos < (2/2.75)) { <BR>return (7.5625*(pos-=(1.5/2.75))*pos + .75); <BR>} else if (pos < (2.5/2.75)) { <BR>return (7.5625*(pos-=(2.25/2.75))*pos + .9375); <BR>} else { <BR>return (7.5625*(pos-=(2.625/2.75))*pos + .984375); <BR>} <BR>} <BR>flower('test2', 'left:300px;padding:10px;border:50px solid #ff0000', { <BR>duration: 1500, <BR>after: function(){ <BR>flower('test1', 'background:#0f0;left:100px;padding-bottom:100px;opacity:1', { <BR>duration: 1234, easing: bounce <BR>}); <BR>} <BR>}); <BR>})(); <BR></script>

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

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/322028.htmlTechArticle做一个普通的动画效果,js是怎么完成的呢.看一下例子 复制代码 代码如下: setInterval(function(){ element.style.left =parseFloat(element.style.left) +(n) +'p...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn