缓冲运动 (基础重点)(速度取整不然跳动)

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
	    *{
	    	margin:0px;
	    	padding:0;
	    }
		.active{
			border:1px solid red;
			width:100px;
			height:50px;		
		}
		
		.div1{
			width:100px;
			height:100px;
			margin-top: 100px;
			background-color: green;
			position:absolute;
			left:1000px;
			top:20px;
		}
    
    .div2{
			width:1px;
			height:500px;
			margin-top: 0px;
			position:absolute;
			left:500px;
			top:0px;
			background-color: black;
		}
	</style>
		
</head>
<body>
	<input type="button" value="开始运动">
	<div class="div1"  >
	</div>
   <div class="div2"></div>

	
	<script>
		//运动的注意点
		//定时器需要定义在运动函数外面以便于清除之前的定时器 var timer=null;
		//在定时器开始之前要记得clearInterval()清除之前的
		//根据物体的目的位置(destination)和物体当前的位置(offsetLeft)来判断向左还是向右移动
		//控制向左还是向右运动就是offsetLeft加上或者减去一个值(speed)逐渐改变物体的left值 
		//加上则向右走 反之向左

		//加速运动问题
		//离目标地越远运动越快  越近则运动越慢-->根据两则的相对距离来动态改变速度(destinatin-offsetLeft)
		//速度一开始过大,导致物体一下子到达目标点---->(destinatin-offsetLeft)/10;
		//速度小数的问题,导致物体会停留在某一个位置;
		//eg: destinetion:300px  
		//1.speed=0.9  offsetLeft=291-->left=291.9px-->291px取整;
		//2.-->offsetLeft=291-->speed=0.9如此循环
		//3.物体在291位置跳动
		//---->向上或者向下取整  整数0.9时候向上取整为1  Math.ceil();
		//-0.9时候向下取整为 -1  Math.floor()
		var timer;
		function startMove(target){
			var div1=document.getElementsByTagName('div')[0];
				var speed=0;
				clearInterval(timer);
				timer=setInterval(function(){
					if(target==div1.offsetLeft){
						clearInterval(timer);
					}else{
						speed=(target-div1.offsetLeft)/10;
						speed=speed>0?Math.ceil(speed):Math.floor(speed);
						div1.style.left=div1.offsetLeft+speed+"px";

					}
				},100);
			
		}

     window.onload=function(){
     	    var input=document.getElementsByTagName('input')[0];
            input.onclick=function(){
           	startMove(500);
           }
           	
           

     }

	</script>
		
		
</body>
</html>

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值