Recently, the Dom drag and drop requirement was involved in the project requirements, so I put together some study notes
Dom events
The event that applies to the element being dragged
- Ondrag is triggered when the element is being dragged (continues to fire throughout)
- Ondragstart Triggered when the user starts dragging an element
- Ondragend Triggered when the user has finished dragging the element
- Ondragleave is called when the mouse moves away from the drag element
Events applied to the target element
- Ondragenter applies to the target element and is called when the drag element enters
- Ondragover is applied to the target element, called when it stays on the target element (continuous firing)
- Ondrop is applied to the target element and is called when the mouse is released over the target element
- Ondragleave is applied to the target element and is called when the mouse moves away from the target element
Drag the elements
Draggable =”true” attribute is added to the dragged element (except for img,a tag, which can be dragged by default).
Does the target element ondrop take effect?
The onDrop event will never fire, because there is no onDragover event defined. The onDragover event is triggered by the target element while the element is being dragged on the target element. The default event (e.preventDefault()) must be cancelled to fire correctly. The onDrop event is triggered by the target element when the dropped element is dropped on top of it.
Demo Code
Use vue to write a simple small demo
<! -- html -->
<div class="box1">
<div v-for="(item, index) in list1" :key="index" draggable @dragstart="onDrag" :k="index">
<p>Name: {{item.name}}</p>
<p>{{item.phone}}</p>
</div>
</div>
<div class="box2" @dragover="ondragover" @drop="onDrop">
<template v-if="list2 && list2.length">
<div v-for="(item, index) in list2" :key="index">
<p>Name: {{item.name}}</p>
<p>{{item.phone}}</p>
</div>
</template>
</div>
Copy the code
// .javascript
data() {
return {
list1: [{name: 'Joe'.phone: 123456789123
},
{
name: 'bill'.phone: 321987654321
},
{
name: "Fifty".phone: "456789432122"}].list2: []}},methods: {
onDrag(e) {
const dataTransfer = e.dataTransfer;
const target = e.target;
const k = target.getAttribute("k");
dataTransfer.setData("k", k);
},
ondragover(e) {
e.preventDefault();
},
onDrop(e) {
const dataTransfer = e.dataTransfer;
const k = +dataTransfer.getData('k');
this.list1 = this.list1.filter((item, index) = > {
if (index === k) {
this.list2.push(item);
}
else {
returnitem; }}); }}Copy the code