js小球运动非常好用

发布于:2023-01-21 ⋅ 阅读:(206) ⋅ 点赞:(0)

在这里插入图片描述

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
			.wrapper{
				width: 500px;
				height: 500px;
				border: 5px solid black;
				margin: 0 auto;
				position: relative;
			}
			.boll{
				width: 80px;
				height: 80px;
				border-radius: 50%;
				background-color: aquamarine;
				position: absolute;
				bottom: 0;
				left: 0;
			}
			.box{
				text-align: center;
			}
			.box button{
				width: 200px;
				height: 50px;
				color: white;
				font-size: 30px;
				border: none;
				background-color: green;
			}
		</style>
	</head>
	<body>
		<div class="box">
			<div class="wrapper">
				<div class="boll"></div>
			</div>
			<button>开始</button>
		</div>
		<script>
			//获取容器
			var _wrapper=document.querySelector(".wrapper");
			//开始按钮
			var _button=document.querySelector("button");
			//小球
			var _boll=document.querySelector(".boll");
			_button.onclick=function(){
				var speedX=6;//x速度
				var speedY=10;//y速度
				var id=setInterval(function(){
					//获取现有的left和top值
					//如果到最右边,需要反向
					if(_wrapper.clientWidth-_boll.offsetLeft<=_boll.offsetWidth){
						speedX*=-1;
					}
					_boll.style.left=(_boll.offsetLeft+speedX)+"px"
					
					//如果到最上边,需要反方向
						
					if(_boll.offsetTop<=0){
						speedY*=-1;
					}
					_boll.style.top=(_boll.offsetTop-speedY)+"px"
					
					//到最下边,需要反向
					if(_wrapper.clientHeight-_boll.offsetTop<=_boll.offsetHeight){
						speedY*=-1;
					}
					
					//到最左边,需要反向
					if(_boll.offsetLeft<=0){
						speedX*=-1;
					}
				},30)
			}
		</script>
	</body>
</html>

网站公告

今日签到

点亮在社区的每一天
去签到