小球碰撞

课后作业

要求: 小球自左向右移动。
扩展: 遇到边界停止。
扩展: 来回反弹的小球。

老师方法

①小球动起来
image
②遇到边界停下
image
也就是关闭计时器的操作
image
③遇到边界返回
image
不用关闭计时器,用正负控制移动方向

提交代码

<head>
	<meta charset="UTF-8">
	<title>小球移动</title>
	<style type="text/css">
		.box {
			width: 800px;
			height: 200px;
			background: #aaa;
			margin: 50px auto;
			position: relative;
		}
		.ball {
			width: 40px;
			height: 40px;
			background: blue;
			border-radius: 25px;
			position: absolute;
			left: 0;
			bottom: 0;
		}
	</style>
</head>
<body>
	<div class="box">
		<div class="ball"></div>
	</div>
	<script>
	var Ball = document.querySelector('.ball'),
	len=760; //总路程
	speed=15; //每次移动距离
	setInterval(function(){
	var Left = Ball.offsetLeft+speed;
		
		if(Left>=len){
	        Left = len;
			speed =-speed ;
	    }
		else if(Left<=0){
			speed = -speed;
		}
		Ball.style.left = Left+'px'; 
	},50) 
	</script>
</body>

缺点是代码没有动态获取窗口的长宽,把len改一下即可

posted @ 2021-07-21 19:42  九尾。  阅读(155)  评论(0编辑  收藏  举报