1. 拖放(Drag 和 Drop) 是HTML5标准的组成部分
2. 拖动开始
* ondragstart: 调用一个函数,drag(event),它规定了被拖动的数据
3. 设置拖动数据:
* setData(): 设置被拖动的数据类型和值
4. 放入位置:
* ondragover: 事件规定在何处防止被拖动的数据
5. 放置:
* ondrop: 当放置被拖动数据是,会发生drop事件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>HTML5 拖放 API</title> <style> .box { width: 400px; height: 400px; border: 1px solid red; border-radius: 24px; padding: 32px; float: left; } #box2 { margin-left: 20px; } #pic{ width: 200px; height: 150px; margin-top: 10px; } </style> </head> <body> <div id="box1" class="box"></div> <div id="box2" class="box"></div> <img id="pic" src="../source/img/12.jpg" alt=""> <script> let box1 = document.getElementById('box1'); let box2 = document.getElementById('box2'); let pic = document.getElementById('pic'); let body = document.body; box1.ondragover = defaultStop; box2.ondragover = defaultStop; pic.ondragstart = function(e) { // 设置拖放数据 console.log('设置数据:', e.dataTransfer) e.dataTransfer.setData('img', 'pic'); } // 放置数据 box1.ondrop = dropData; box2.ondrop = dropData; function defaultStop (e) { e.preventDefault(); } function dropData(e) { e.preventDefault(); let img = document.getElementById(e.dataTransfer.getData('img')); e.target.appendChild(img); } </script> </body> </html>