关于缓冲运动中的小问题

window.onload=function(){
			var div1 = document.getElementById('div1');
			div1.onmouseover=function(){
				startMove(0);
			}
			div1.onmouseout=function(){
				startMove(-200);
			}
		}
		var timer = null;
		function startMove(target){
			clearInterval(timer);
			var div1 = document.getElementById('div1');
			timer=setInterval(function(){
				var speed =(target-div1.offsetLeft)/20;
				speed = speed>0? Math.ceil(speed):Math.floor(speed);
				if(div1.offsetLeft == target){
					clearInterval(timer);
				}else
				div1.style.left =div1.offsetLeft+speed+'px';
			},20);
		}

原理:   speed值逐渐变小,所以是减速运动。

若无speed向上向下取整操作,运动时left会分别停在-8.55和-190.5.

原因是offsetLeft会round()取整。停在-190.5是因为offsetLeft取值时把-190.5取为-190。speed=(-200-(-190))/20=-0.5;最后div1.offsetLeft+speed+'px'一直等于-190.5。-8.55同理。

若加上向上向下取整,最后的speed都会取为1 or -1,然后每次速度为1向目标值靠拢。

猜你喜欢

转载自blog.csdn.net/qq_32522799/article/details/85013463