js实现拖拽

时间:2023-02-23 12:02:50

mousedown、mousemove、mouseup监听这三个事件。

  • offsetLeft:返回元素与有定位的父类的上左边距,如果父类都没有定位,那么返回相对于页面的上左边距。
  • scrollTop:滚动条滚动过的高度。
  • 要对移动对象使用绝对定位,脱离文档流,相对定位不会脱离文档流,还会占据空间,除非使用z-index
  • 元素的位置x = 鼠标现在的位置x-(鼠标之前的位置x-元素的左偏移量)
  • 移动和鼠标松开后是对document的绑定,移动过程中是监听移动的行为,用window.mousemove

图片示意

js实现拖拽

代码实现

<style>
img {
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
<body style="margin: 0;">
<img id='dv' src="https://picsum.photos/200/300" />
</body>
<script>
//获取元素
var dv = document.getElementById('dv');
var x = 0, y = 0, l = 0, t = 0;
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';
console.log({ x })
console.log({ y })
console.log({ l })
console.log({ t })
}
//鼠标移动
window.onmousemove = function (e) {
e.preventDefault()
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';
}
</script>