JavaScript:div的拖拽问题

创建一个可以拖拽的div,并让鼠标点哪里就从哪里开始拖拽


学习过程中遇到的一个练习题,自己写的时候觉得先行保存固定变量的概念挺有用的

<style>
	#show {
				width: 100px;
				height: 100px;
				border: 1px solid black;
				background-color: red;
				position: absolute;
			}
</style>
<script>
				var show = document.getElementById("show");
				var msg = document.getElementById("show");
				show.onmousedown = function(ev) {
					var x = ev.clientX;
					var y = ev.clientY;//获取鼠标点击时的坐标
					var left = x - show.offsetLeft;
					var top = y - show.offsetTop;//在鼠标按下时先把鼠标坐标到div边框的距离保存下来
					document.onmousemove = function(ev) {	
						var x = ev.clientX;
						var y = ev.clientY;//获取新的鼠标坐标
						show.style.left = x - left + "px";
						show.style.top = y - top + "px";//用新的坐标减去那段距离
					}
					document.onmouseup = function() {
						document.onmousemove = null;
						document.onmouseup = null;
					}
				}
</script>
<body>
		<div id="show">
</body>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值