DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Documenttitle>
<style>
ul {
width: 1000px;
height: 200px;
background: palegreen;
}
main {
border: 2px solid #333;
height: 300px;
width: 1200px;
}
style>
head>
<body>
<ul id="oriDiv" draggable="true">
<li>111111li>
<li>222222li>
<li>333333li>
<li>444444li>
<li>555555li>
ul>
<main id="main">main>
<script>
oriDiv.ondragstart = function () {
console.log('drag start')
}
main.ondragenter = function () {
console.log('drag enter')
}
main.ondragleave = function () {
console.log('drag leave')
}
main.ondragover = function (e) {
e.preventDefault()
console.log('drag over')
}
// @WARN:使用drop时注意,需要首先将drop事件的前一个事件dragover的浏览器默认操作禁止,
// 才可以触发drop事件。
main.ondrop = function () {
console.log('drop ...')
}
/**
* source
*/
oriDiv.ondragstart = (e) => {
console.log('clearing data ...')
e.dataTransfer.cleanData()
console.log('setting data ...')
e.dataTransfer.setData('name', JSON.stringify({ name: 'xiaoming' }))
}
/**
* target
*/
main.ondragover = (e) => {
e.preventDefault()
}
main.ondrop = (e) => {
console.log('getting data ...')
data = JSON.parse(e.dataTransfer.getData('name'))
console.log(data.name)
}
/**
* Example code
*/
const img = document.querySelectorAll('img')
const des = document.querySelectorAll('div')
for (let i = 0; i < des.length; i++) {
img[i].ondragstart = (e) => {
e.dataTransfer.setData('id', e.target.id)
}
des[i].ondragover = (e) => {
e.preventDefault()
}
des[i].ondrop = (e) => {
const id = e.dataTransfer.getData('id')
this.appendChild(document.getElementById(id))
}
}
script>
body>
html>