小球运动(JS小练习)

JS小练习 小球运动

先上效果图

小球运动

代码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
			*{
				margin: 0;
				padding: 0;
			}
			.box{
				width: 500px;
				margin: 0 auto;
				text-align: center;
			}
			.wall{
				width: 500px;
				height: 500px;
				border: 5px solid lightgrey;
				position: relative;
			}
			button{
				width: 200px;
				line-height: 50px;
				color: white;
				font-size: 20px;
				font-weight: bolder;
				background-color: skyblue;
				border: none;
				outline: none;
				margin-top: 10px;
			}
			.boll{
				width: 80px;
				height: 80px;
				border-radius: 50%;
				background-color: cyan;
				position: absolute;
				bottom: 0;
				left: 0;
			}
		</style>
	</head>
	<body>
		<div class="box">
			<div class="wall">
				<div class="boll"></div>
			</div>
			<button>开始</button>
		</div>
		<script>
			// 获取容器
			var _wall = document.querySelector('.wall');
			// 获取开始按钮
			var _button = document.querySelector('button');
			// 获取小球
			var _boll = document.querySelector('.boll');
			_button.onclick = function(){
				// XY轴运动速度
				var X = 5;
				var Y = 8;
				var id = setInterval(function(){
					_boll.style.left = _boll.offsetLeft+X+'px';
					_boll.style.top = _boll.offsetTop-Y+'px';
					// 到最右边,反转运动方向
					if(_wall.clientWidth-_boll.offsetLeft<=_boll.offsetWidth){
						X*=-1;
					}
					// 到最上边,反转运动方向
					if(_boll.offsetTop<=0){
						Y*=-1;
					}
					// 到最左边,反转运动方向
					if(_boll.offsetLeft<=0){
						X*=-1;
					}
					// 到最下边,反转运动方向
					if(_wall.clientHeight-_boll.offsetTop<=_boll.offsetHeight){
						Y*=-1;
					}
				},10)
			}
		</script>
	</body>
</html>

总结用到的知识

  元素的可视距离: tag.clientHeight,tag.clientWidth

  元素控件距离: tag.offsetHeight,tag.offsetWidth

  被撑开的距离: tag.scrollHieght,tag.scrollWidth

  元素的位置: tag.offsetLeft,tag.offsetTop

今天就到这,下课!♥

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值