碰撞运动

1、点击开始运动,盒子开始运动,碰到/超出可是区范围,盒子返回来运动。 

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>碰撞运动</title>
	<style>
		#div1{
			width: 260px;
			height: 160px;
			background: url(pz.jpg) center center / cover no-repeat;
			position: absolute;
			left: 130px;
		}
	</style>
	<script>
		var iSpeedX=5;
		var iSpeedY=6;
		var timer=null;
		window.onload=function(){
			var oDiv=document.getElementById("div1");
			var oBtn=document.getElementById("btn");
			oBtn.onclick=function(){
				startMove(oDiv);
			}
		}
		function startMove(obj){
			clearInterval(timer);
			timer=setInterval(function(){
				var l=obj.offsetLeft+iSpeedX;
				var t=obj.offsetTop+iSpeedY;
				if (l>document.documentElement.clientWidth-obj.offsetWidth) {
					iSpeedX*=-1;
					l=document.documentElement.clientWidth-obj.offsetWidth;
				}
				else if(l<0){
					iSpeedX*=-1;
				}
				if (t>document.documentElement.clientHeight-obj.offsetHeight) {
					iSpeedY*=-1;
					t=document.documentElement.clientHeight-obj.offsetHeight;
				}
				else if(t<0){
					iSpeedY*=-1;
				}

				obj.style.left=l+'px';
				obj.style.top=t+'px';
			},30);
		}
	</script>
</head>
<body>
	<div id="div1"></div>
	<input type="button" value="点击开始运动" id="btn">
</body>
</html>

结果展示:

 

 

猜你喜欢

转载自blog.csdn.net/zhangqling/article/details/84635838