CSS+JS制作一个在浏览器内自由反弹的方框

做为《JS的DOM操作详解》中的一个进阶练习,制作一个可以在浏览器内自由反弹的方框。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<script src="js/test.js" type="text/javascript" charset="utf-8"></script>
		<title></title>				
	</head>
	<style type="text/css">
		* {
			margin: 0;
			padding: 0;
		}
		#box {
			background-color: beige;
			height: 100px;
			width: 100px;
			top: 0px;
			left: 0px;
			position: relative;
		}
		p {
			text-align: center;
			line-height: 100px;
		}
	</style>
	<body>	
	<div id="box">
		<p>Move me!</p>
	</div>
	<button type="button" onclick="changeDiv()">Boom!</button>
	<button type="button" onclick="stopChangeDiv()">Stop!</button>
	<script type="text/javascript">
		var box=document.getElementById('box');
		var timer;
		function changeDiv(){
			var x=10;
			var y=10;
			timer = window.setInterval(()=>{
				var left=parseInt(window.getComputedStyle(box,null)['left']);
				var top=parseInt(window.getComputedStyle(box,null)['top']);
				var height=parseInt(window.getComputedStyle(box,null)['height']);
				var width=parseInt(window.getComputedStyle(box,null)['width']);
				var w=document.documentElement.clientWidth || document.body.clientWidth || window.innerWidth;
				var h=document.documentElement.clientHeight || document.body.clientHeight || window.innerHeight;
				if(left+width>w-10){
					x=-10;
				}else if(left<0){
					x=10;
				};
				if(top+height>h-10){
					y=-10;
				}else if(top<0){
					y=10;
				};
				box.style.left=left+x+'px';
				box.style.top=top+y+'px';
				console.log(left,x,top,y);
			},100)
		}
		
		function stopChangeDiv(){
			window.clearInterval(timer);
		}
	</script>
	</body>
</html>

需要注意的知识点:

  • parseInt会获取第一个数字到第一个非数字之间的内容,所以可以顺利去掉单位
  • 判断向下和向右临界点的时候加了10px的偏移,避免出现滚动条

我是T型人小付,一位坚持终身学习的互联网从业者。喜欢我的博客欢迎在csdn上关注我,如果有问题欢迎在底下的评论区交流,谢谢。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值