前端开发之图层拖拽与调整大小

<!DOCTYPE html>
<html lang="cn">
	<head>
		<meta charset="UTF-8">
		<title>图层拖拽与调整大小</title>
		<style>
			.box {
				width: 200px;
				height: 200px;
				background-color: skyblue;
				border: 2px solid #ccc;
				cursor: pointer;
				position: absolute;
				overflow: hidden;
				resize: both;
				top: 20px;
				left: 100px;
				min-width: 120px;
				min-height: 90px;
				max-width: 400px;
				max-height: 300px;
			}

			.box:hover,
			.box:focus {
				outline: none;
				border: 2px solid red;
			}
		</style>
	</head>
	<body>

		<div class="box" id="nbox" tabindex="2" style="top:400px;"></div>
		<div class="box" id="box" tabindex="1"></div>

	</body>
	<script>
		var box = document.getElementById("box");
		box.onmousedown = function(env) {
			// 兼容event事件
			var env = env || window.event;
			// 获取鼠标的坐标
			var x = env.clientX;
			var y = env.clientY;
			//  获取元素的坐标
			var left = box.offsetLeft;
			var top = box.offsetTop;
			// 获取鼠标在元素中的坐标
			var x_left = x - left;
			var y_top = y - top;
			//  鼠标点击后改变颜色
			box.style.background = "red";
			//  元素的移动事件函数
			box.onmousemove = function(env) {
				// 兼容event事件
				var env = env || window.event;
				//  获取元素移动时的鼠标的坐标
				var x = env.clientX;
				var y = env.clientY;
				//  元素的移动坐标
				box.style.left = (x - x_left) + "px";
				box.style.top = (y - y_top) + "px";
			}
		};
		//  鼠标弹出的事件函数
		box.onmouseup = function() {
			box.style.background = "skyblue";
			// 在鼠标弹出后再次调用元素的鼠标移动事件
			box.onmousemove = function() {};
		};
	</script>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿赛工作室

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值