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 @   JackieDYH  阅读(3)  评论(0编辑  收藏  举报  
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示