Js-动态边框鼠标拖动

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<meta charset="utf-8">
	<style type="text/css">
	* {
		margin:0;
		padding:0;
	}
	.box {
		width:100px;
		height:100px;
		background:red;
		position:absolute;
		left:0;
		top:0;
	}
	#wrap {
		position:relative;
		width:500px;
		height:500px;
		background:#ccc;
		margin:50px auto;
	}
	
	</style>
</head>
<body>
	<div id="wrap">
		<div class="box">
		</div>
	</div>
	<script type="text/javascript">
		var oBox = document.querySelector(".box");
		var owrap = document.querySelector("#wrap");
		oBox.onmousedown = function(ev) {
			//获取window.event对象兼容写法
			var ev = window.event || ev;
			//当前鼠标点击位置距离容器的x轴值
			var disX = ev.clientX - this.offsetLeft;
			//当前鼠标点击位置距离容器的y轴值
			var disY = ev.clientY - this.offsetTop;
			//鼠标拖动事件
			document.onmousemove = function(ev) {
				var ev = window.event || ev;
				//鼠标拖动容器在wrap容器中的x轴值
				var L = ev.clientX - disX;
				//鼠标拖动容器在wrap容器中的y轴值
				var T = ev.clientY - disY;
				//不允许拖动出左边界的判断
				if (L < 0) {
					L = 0
				//不允许拖动出右边界的判断
				} else if (L > owrap.offsetWidth - oBox.offsetWidth) {
					//若鼠标超出边界值,则将容器固定在边界
					L = owrap.offsetWidth - oBox.offsetWidth
				}
				//不允许拖动出上边界的判断
				if (T < 0) {
					T = 0
				//不允许拖动出下边界的判断
				} else if (T > owrap.offsetWidth - oBox.offsetHeight) {
					//若鼠标超出边界值,则将容器固定在边界
					T = owrap.offsetWidth - oBox.offsetHeight;
				}
				//赋值移动容器的x轴值
				oBox.style.left = L + "px";
				//赋值移动容器的y轴值
				oBox.style.top = T + "px";
			}
			//鼠标松开初始化鼠标事件
			document.onmouseup = function() {
				document.onmousemove = null;
				document.onmouseup = null;
			}
		}
	</script>
</body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值