<!--
* @Descripttion:
* @Version:
* @Author: bigzhad
* @Date: 2022-11-25 10:17:24
* @LastEditors:
* @LastEditTime: 2022-11-25 10:29:39
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#div_main {
width: 200px;
height: 200px;
background: #ff0;
position: absolute;
}
</style>
<script src="common.js"></script>
</head>
<body>
<div id="div_main"></div>
<script !src="">
$('div_main').onmousedown = function (evt) {
// 鼠标按下时候的点
let x0 = evt.offsetX;
let y0 = evt.offsetY;
document.onmousemove = function (evt) {
// 目标和鼠标一起移动
// 1. 获取鼠标的坐标
let x = evt.pageX;
let y = evt.pageY;
// 2. 让div_main移动到坐标的位置
$('div_main').style.left = x - x0 + 'px';
$('div_main').style.top = y - y0 + 'px';
}
}
$('div_main').onmouseup = function () {
// 当鼠标抬起 让移动事件失效
document.onmousemove = null;
}
</script>
</body>
</html>
01-04
570
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
10-24
620
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
03-30
44
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)