不错的HTML5拖拽小案例

非常个性的拖拽,可以实现两个模块之间的小圆球互相移动,复制全部代码试试吧。如果喜欢记得保存书签收藏哦!

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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>拖拽案例</title>
<style>
.one{
width: 400px;
height: 400px;
border: solid 1px #000;
}
.one div {
width: 98px;
height: 98px;
border: solid 1px #000;
border-radius: 50%;
float: left;
text-align: center;
line-height: 98px;
background: pink;
}
.two{
width: 400px;
height: 400px;
border: solid 1px #000;
position: absolute;
top: 200px;
right: 100px;
}
.two div {
width: 98px;
height: 98px;
border: solid 1px #000;
border-radius: 50%;
float: left;
text-align: center;
line-height: 98px;
background: pink;
}
</style>
</head>
<body>
<div class = 'one'>
<div draggable = "true">1</div>
<div draggable = "true">2</div>
<div draggable = "true">3</div>
<div draggable = "true">4</div>
<div draggable = "true">5</div>
<div draggable = "true">6</div>
<div draggable = "true">7</div>
<div draggable = "true">8</div>
</div>
<div class = 'two'>
</div>
</body>
<script>
//获取所有one里面的小盒子分别绑定拖拽事件
var boxs = document.querySelectorAll(".one div");
var one = document.querySelector(".one");
//目标元素
var two = document.querySelector(".two");
//临时的盒子,用于存放当前拖拽的元素
var temp = null;
for(var i = 0;i<boxs.length;i++){
boxs[i].ondragstart = function(){
temp = this;
console.log(temp);
}
//拖拽结束,清空temp
boxs[i].ondragend = function(){
temp = null;
console.log(temp);
}
}
//目标元素拖拽事件
two.ondragover = function(e){
//阻止拖拽默认行为
e.preventDefault();
}
two.ondrop = function(){
this.appendChild(temp);
}
//目标元素拖拽事件
one.ondragover = function(e){
//阻止拖拽默认行为
e.preventDefault();
}
one.ondrop = function(){
this.appendChild(temp);
}
</script>
</html>

文章目录