首先滓走,設(shè)置一個(gè)拖拽元素和被拖拽到的元素权薯,并要給拖拽元素添加draggable="true"讼呢,來(lái)允許元素被拖拽撩鹿。
HTML代碼
<div class="box1">
<!--draggable 允許該元素被拖動(dòng)-->
<div class="box" draggable="true">
</div>
</div>
<div class="box2">
</div>
簡(jiǎn)單的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;
}
拖動(dòng)時(shí)會(huì)觸發(fā)的事件:
//拖拽元素
var box = document.querySelector(".box");
//目標(biāo)元素
var target = document.querySelector(".box2");
box.ondragstart = function () {
console.log(1,"開始拖拽");
}
box.ondrag = function () {
console.log(2,"拖拽中");
}
box.ondragend = function () {
console.log(3,"拖拽結(jié)束");
}
target.ondragenter = function () {
console.log(4,"進(jìn)入目標(biāo)元素");
}
target.ondragleave = function () {
console.log(5,"離開目標(biāo)元素");
}
target.ondragover = function () {
console.log(6,"在目標(biāo)元素上移動(dòng)");
}
target.ondrop = function () {
console.log(7,"在目標(biāo)元素上方法");
}