javascript 多物体任意运动框架

每个复杂的运动效果都是由简单的效果组成的,我们可以为简单的效果制定一个框架,也就是写一个通用函数,这样可以对元素的任何属性进行变换,复杂的效果就可以很容易实现。

注意事项:

  1. 当变换元素的透明度时,需要做特殊处理
  2. 如果变换元素宽度时,对于有border的元素,如果我们使用obj.offsetWidth来取得元素宽度时,会出现错误,因为offsetWidth包括边框。如果边框是1px,定时函数中调用,obj.style.width=obj.offsetWidth-1+‘px’;,我们会发现元素的宽度不仅没有变小,反而会变大。这也是我们使用我们自定义的getStyle()取得元素宽度的原因,而没有使用offsetWidth这一类的属性。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>New Web Project</title>
		<style>
			div{
				width:200px;
				height:200px;
				float:left;
				background:red;
				margin:10px;
				
			}
		</style>
		<script>
			function getStyle(obj,name)
			{
				if(obj.currentStyle)
				{
					return obj.currentStyle[name];
				}
				else
				{
					return getComputedStyle(obj,null)[name];
				}
			}
			window.οnlοad=function(){
				var objs=document.getElementsByTagName('div');
				objs[1].οnmοuseοver=function(){
					startMove(this,'width',400);
				};
				objs[1].οnmοuseοut=function(){
					startMove(this,'width',200);
				};
				objs[0].οnmοuseοver=function(){
					startMove(this,'height',400);
				};
				objs[0].οnmοuseοut=function(){
					startMove(this,'height',200);
				};
				objs[2].οnmοuseοver=function(){
					startMove(this,'opacity',100);
				};
				objs[2].οnmοuseοut=function(){
					startMove(this,'opacity',30);
				};
			};
			
			function startMove(obj,atrr,itarget){
				clearInterval(obj.timer);
				obj.timer=setInterval(function(){
					var nowValue;
					if(atrr=='opacity')
					{
						nowValue=Math.round(parseFloat(getStyle(obj,atrr))*100);//计算机运算会有错误,需要取约数
						document.title=nowValue;
					}
					else
					{
						nowValue=parseInt(getStyle(obj,atrr));	
					}
					
						
					var speed=(itarget-nowValue)/5;
					speed=speed>0?Math.ceil(speed):Math.floor(speed);
					if(nowValue==itarget)
					{
						clearInterval(obj.timer);
					}
					else
					{
						if(atrr=='opacity')
						{
							obj.style[atrr]=(nowValue+speed)/100;
							obj.style.filter='alpha(opacity:'+(nowValue+speed)+')';//IE低版本设置
						}
						else
						{
							obj.style[atrr]=nowValue+speed+'px';
						}
						
					}
					
				},30);
			}
			
		</script>
	</head>
	<body>
		<div></div>
		<div></div>
		<div style="opacity: 0.3; filter: alpha(opacity:30);"></div>
	</body>
</html>

运行效果图:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值