JavaScript 動畫 3---緩衝動畫

1、要點

速度:var speed =(iTarget-cDiv1.offsetLeft)/10;   //10爲運動係數 緩緩運動html

爲了不速度爲小數:speed = speed>0?Math.ceil(speed):Math.floor(speed);
  //若是速度大於0 向上取整;速度小於0向下取整函數

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	<style>
	body,div,span{
		margin: 0;
		padding: 0;
	}
	#div1{
		width: 200px;
		height:200px;
		background:red;
		position: relative;
		left: -200px;
	}
	#div1 span{
		width: 20px;
		height: 100px;
		background: blue;
		position: absolute;
		left: 200px;
		top: 50px;
	}
	</style>
	
	<script>
	//Math.floor(9.99); //向下取整 9
	//Math.ceil(9.9);//向上取整 10
	var timer = null;
		window.onload = function(){
			
			var cDiv1 = document.getElementById('div1');
			
			//鼠標移入
			cDiv1.onmouseover = function(){
				startMove(0); //移動函數
			}
			
			//鼠標移出
			cDiv1.onmouseout = function(){
			    startMove(-200); //移動函數
			}
			
			/**
			 * @param {目標} iTarget
			 */
			function startMove(iTarget){
				
				clearInterval(timer); //爲了不定時器屢次觸發
				
				var cDiv1 = document.getElementById('div1');
				timer = setInterval(function(){
					var speed =(iTarget-cDiv1.offsetLeft)/10; 
					//10爲運動係數 緩緩運動
					speed = speed>0?Math.ceil(speed):Math.floor(speed);
					//若是速度大於0 向上取整;速度小於0向下取整
					if(cDiv1.offsetLeft == iTarget){
						clearInterval(timer); //中止定時器
					}else{
					cDiv1.style.left = cDiv1.offsetLeft+speed+'px'; //offsetLeft當前位置的值
					}
				},30)
			}//每30毫秒動一下
		}
		
		
	</script>
	</head>
	<body>
		<div id="div1">
			<span id="share">側邊廣告</span>
		</div>
	</body>
</html>
相關文章
相關標籤/搜索