【前端小实战】碰撞检测和物体吸附效果

一、效果展示

在这里插入图片描述

二、完整代码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		
		<style type="text/css">
			#collide {
				height: 600px;
				width: 100%;
				position: relative;
			}
			
			#move {
				position: absolute;
				width: 100px;
				height: 100px;
				background-color: red;
			}
			
			#box {
				position: absolute;
				width: 200px;
				height: 200px;
				background-color: gray;
				top: 0;
				bottom: 0;
				left: 0;
				right: 0;
				margin: auto;
			}
		</style>
	</head>
	<body>
		<div id="collide">
			<div id="box"></div>
			<div id="move"></div>
		</div>
	</body>
	
	<script type="text/javascript">
		var move = document.getElementById("move");
		var box = document.getElementById("box");
		
		// 鼠标按下时执行事件
		move.onmousedown = function(e) {
			var t = e.clientY - move.offsetTop;
			var l = e.clientX - move.offsetLeft;
			
			// 移动时执行事件
			document.onmousemove = function(e) {
				var top = e.clientY - t;
				var left = e.clientX - l;
				
				// 通过改变 move 的 left 和 top 值来实现方块移动
				move.style.top = top + "px";
				move.style.left = left + "px";
				
				// 吸附效果
				if(top + move.offsetHeight >= box.offsetTop		// 上下边缘检测
				&& top <= box.offsetTop + box.offsetHeight) { 
					// 左侧吸附
					if(left + move.offsetWidth + 50 >= box.offsetLeft
					&& left + move.offsetWidth<= box.offsetLeft + box.offsetWidth) {
						left = box.offsetLeft - move.offsetWidth;
						move.style.left = left + "px";
					}
					// 右侧吸附
					else if(left - 50 <= box.offsetLeft + box.offsetWidth
					&& left > box.offsetLeft + box.offsetWidth - move.offsetWidth) {
						left = box.offsetLeft + box.offsetWidth;
						move.style.left = left + "px";
					}
				}
				
				
				// 碰撞检测
				if(	//碰到了
					move.offsetLeft + move.offsetWidth >= box.offsetLeft
					&& move.offsetLeft <= box.offsetLeft + box.offsetWidth
					&& move.offsetTop + move.offsetHeight >= box.offsetTop
					&& move.offsetTop <= box.offsetTop + box.offsetHeight
				) {
					box.style.backgroundColor = "yellow";
				} else {
					box.style.backgroundColor = "gray";
				}
			}
		}
		
		// 当鼠标松开时,停止移动事件执行
		move.onmouseup = document.onmouseup =  function() {
			document.onmousemove = null;
		}
	</script>
</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值