【代码】鼠标拖动效果

前言

使用JS实现鼠标拖动div效果

源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
margin: 0px;
padding: 0px;
}

.cur {
position: absolute;
width: 200px;
height: 200px;
background: lightskyblue;
}
</style>
</head>
<body>

<div class="cur"></div>

</body>
</html>
<script>
let div = document.querySelector(".cur");
// 绑定鼠标按下事件
div.onmousedown = function(event) {
let e = event || window.event;
// console.log("鼠标按下");

let startX = e.offsetX;
let startY = e.offsetY;

// 绑定鼠标移动事件
document.onmousemove = function(event1) {
let e1 = event1 || window.event;
// console.log("鼠标移动");

// 元素拖拽
div.style.left = e1.clientX - startX + "px";
div.style.top = e1.clientY - startY + "px";

}
}

// 绑定鼠标抬起事件
document.onmouseup = function() {
// 清除鼠标移动事件
document.onmousemove = null;
}
</script>

完成

参考文献

哔哩哔哩——web前端小清风