let disX = e.clientX - el.offsetLeft;
let disY = e.clientY - el.offsetTop;
document.onmousemove = function (e) {
//计算需要移动的距离
let t = e.clientX - disX;
let P = e.clientY - disY;
//移动当前元素
if (t >= 0 && t <= window.innerWidth - el.offsetWidth) {
el.style.left = t + ‘px’;
}
//移动当前元素
if (P >= 0 && P <= window.innerHeight - el.offsetHeight ) {
el.style.top = P + ‘px’;
}
};
//鼠标松开时,注销鼠标事件,停止元素拖拽。
document.onmouseup = function (e) {
document.onmousemove = null;
document.onmouseup = null;
};
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200303192827936.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80Mjc3NjExMQ=