JavaScript 运动框架

来源:互联网 发布:java idea maven 打包 编辑:程序博客网 时间:2024/05/16 07:00

JavaScript的运动,即让某元素的某些属性由一个值变到另一个值的过程。如让div的width属性由200px变到400px,opacity属性由0.3变到1.0,就是一个运动过程。


实现运动要注意以下方面:

1. 匀速运动(改变left、right、width、height、opacity等属性)

2. 缓冲运动(速度是变化的)

3. 多物体运动(注意所有东西都不能共用,否则容易产生冲突,如定时器timer)

4. 获取任意属性值(封装一个getStyle函数)

5. 链式运动(串行)

6. 同时运动(并行,同时改变多个属性,需要使用 json)


封装好的getStyle函数,在下面的运动框架中会用到:

function getStyle(obj,attr){if(obj.currentStyle){return obj.currentStyle[attr];  //针对IE}else{return getComputedStyle(obj,false)[attr];  //针对Firefox}}


万能的运动框架:

function Move(obj,json,callback){var flag=true;  //标志变量,为true表示所有运动都到达目标值clearInterval(obj.timer);obj.timer=setInterval(function(){flag=true;for(var attr in json){//获取当前值var curr=0;if(attr=='opacity'){curr=Math.round(parseFloat(getStyle(obj,attr))*100);  //parseFloat可解析字符串返回浮点数//round四舍五入}else{curr=parseInt(getStyle(obj,attr));  //parseInt可解析字符串返回整数}//计算速度var speed=(json[attr]-curr)/10;speed=speed>0?Math.ceil(speed):Math.floor(speed);//检测是否停止if(curr!=json[attr]){flag=false;  //有一个属性未达目标值,就把flag变成false}if(attr=='opacity'){obj.style.filter='alpha(opacity:'+(curr+speed)+')';  //针对IEobj.style.opacity=(curr+speed)/100;  //针对Firefox和Chrome}else{obj.style[attr]=curr+speed+'px';}}if(flag){clearInterval(obj.timer);if(callback){callback();}}},30);}


调用上述运动框架的实例:

var div_icon=document.getElementById('icon');var aList=div_icon.getElementsByTagName('a');for(var i=0;i<aList.length;i++){<span style="white-space:pre"></span>aList[i].onmouseover=function(){<span style="white-space:pre"></span>var _this=this.getElementsByTagName('i')[0];<span style="white-space:pre"></span>Move(_this,{top:-70,opacity:0},function(){<span style="white-space:pre"></span>_this.style.top=30+'px';<span style="white-space:pre"></span>Move(_this,{top:10,opacity:100});<span style="white-space:pre"></span>});<span style="white-space:pre"></span>}}

好了,以上就是用JavaScript编写的运动框架。此外,jQuery中的animate函数也可以方便实现上述功能:

$(function(){$('#icon a').mouseenter(function(){$(this).find('i').animate({top:"-70px",opacity:"0"}, 300,function(){  //动画速度为300ms$(this).css({top:"30px"});$(this).animate({top:"10px",opacity:"1"}, 200);});})})



源自慕课网教学视频






0 0