学习目标: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';
}
}
学习内容:
鼠标拖拽盒子在电脑屏幕上移动