js拖拽盒子移动效果

学习目标:js拖拽盒子移动效果

css部分:
#legend{
position: fixed;
bottom: 80px;
left: 100px;
width: 143px;
height: 328px;
z-index: 999;
backdrop-filter: blur(20px);

}

body部分

<div id='legend'>   图例 </div>

js部分

// 图例拖拽
	drag('legend');
	function drag(id){
		var dv = document.getElementById(id);
		var isDown = false;
		//鼠标按下事件
		dv.onmousedown = function(e) {
			//获取x坐标和y坐标
			x = e.clientX;
			y = e.clientY;


			//获取左部和顶部的偏移量
			l = dv.offsetLeft;
			t = dv.offsetTop;

			//开关打开
			isDown = true;
			//设置样式
			dv.style.cursor = 'move';
		}
		//鼠标移动
		dv.onmousemove = function(e) {
			if (isDown == false) {
				return;
			}
			//获取x和y
			var nx = e.clientX;
			var ny = e.clientY;
			//计算移动后的左偏移量和顶部的偏移量
			var nl = nx - (x - l);
			var nt = ny - (y - t);
			dv.style.left = nl + 'px';//盒子顶角左侧顶角的位置
			dv.style.top = nt + 'px';
		}
		//鼠标抬起事件
		dv.onmouseup = function() {
			//开关关闭
			isDown = false;
			dv.style.cursor = 'default';
		}
	}

学习内容:

鼠标拖拽盒子在电脑屏幕上移动

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值