JavaScript 运动框架

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)+')';  //针对IE
				obj.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].οnmοuseοver=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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值