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.onload=function  () {
			var btn=document.getElementById('btn');
			var div1=document.getElementById('div1');

			var Time=null;
			var speed=0;
			btn.onclick=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)://防止多次点击事件的产生



javascript---之自由落体运动实现,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。