js-元素碰撞检测-变色

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
			#box1 {
				width: 100px;
				height: 100px;
				background: red;
				position: absolute;
			}

			#box2 {
				width: 300px;
				height: 300px;
				background: green;
				position: absolute;
				left: 500px;
				top: 200px;
			}
		</style>
		<script type="text/javascript">
			window.onload = function() {
				var boxS = document.getElementsByTagName('div');
				//1 按下
				boxS[0].onmousedown = function(e) {
					var ev = window.event || e;
					//纵向a:clientY-offsetTop  横向距离b:clientX-offsetLeft
					//差值
					var a = ev.clientY - this.offsetTop;
					var b = ev.clientX - this.offsetLeft;
					//拖拽
					document.onmousemove = function(e) {
						var ev = window.event || e;
						//实际位置
						var x = ev.clientX - b;
						var y = ev.clientY - a;
						if (x >= boxS[1].offsetLeft - boxS[0].offsetWidth && x <= boxS[1].offsetLeft + boxS[1].offsetWidth && y >=
							boxS[1].offsetTop - boxS[0].offsetHeight && y < boxS[1].offsetTop + boxS[1].offsetHeight) {
							boxS[1].style.background = 'yellow';
						} else {
							boxS[1].style.background = 'green';
						}
						boxS[0].style.left = x + 'px';
						boxS[0].style.top = y + 'px';
					}
				}
				boxS[0].onmouseup = function() {
					document.onmousemove = null;
				}
			}
		</script>
	</head>
	<body>
		<div id="box1"></div>
		<div id="box2"></div>
	</body>
</html>

 

posted @ 2020-04-09 21:30  JackieDYH  阅读(2)  评论(0编辑  收藏  举报  来源