javascript---之自由落體運動實現

實現自由落體運動需要理解的幾個簡單屬性:

clientHeight:瀏覽器客戶端整體高度

offsetHeight:對象(比如div)的高度

offsetTop:對象離客戶端最頂端的距離

簡單demo如下:

<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>free_movement</title>
	<style type="text/css">
		#div1{
			position: absolute;
			height: 100px;
			width: 100px;
			background: red;
		}
	</style>
	<script type="text/javascript">
		window.οnlοad=function  () {
			var btn=document.getElementById('btn');
			var div1=document.getElementById('div1');

			var Time=null;
			var speed=0;
			btn.οnclick=function () {
				startMove();
			}

			function startMove () {
				clearInterval(Time);
				Time=setInterval(function(){
					speed+= 3;
					var T = div1.offsetTop + speed;
					if(T > document.documentElement.clientHeight - div1.offsetHeight){
						T = document.documentElement.clientHeight - div1.offsetHeight;
						speed *= -1;
						speed *= 0.75;
					}
					div1.style.top=T+'px';
				}, 30)
			}
		}
	</script>
</head>
<body>
	<input type='button' value='開始運動' id="btn">
	<div id="div1"></div>
</body>
</html>

注:clearTnterval(Time)://防止多次點擊事件的產生



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章