首先,设置一个拖拽元素和被拖拽到的元素,并要给拖拽元素添加draggable="true",来允许元素被拖拽。
HTML代码
<div class="box1">
<!--draggable 允许该元素被拖动-->
<div class="box" draggable="true">
</div>
</div>
<div class="box2">
</div>
简单的CSS样式
.box1 {
width: 300px;
height: 200px;
border: 1px solid;
margin: 50px;
float: left;
}
.box2 {
width: 300px;
height: 200px;
border: 1px solid;
margin-top: 50px;
float: left;
}
.box {
width: 50px;
height: 50px;
background: red;
}
拖动时会触发的事件:
//拖拽元素
var box = document.querySelector(".box");
//目标元素
var target = document.querySelector(".box2");
box.ondragstart = function () {
console.log(1,"开始拖拽");
}
box.ondrag = function () {
console.log(2,"拖拽中");
}
box.ondragend = function () {
console.log(3,"拖拽结束");
}
target.ondragenter = function () {
console.log(4,"进入目标元素");
}
target.ondragleave = function () {
console.log(5,"离开目标元素");
}
target.ondragover = function () {
console.log(6,"在目标元素上移动");
}
target.ondrop = function () {
console.log(7,"在目标元素上方法");
}