拖动 Drag
1.在对Drag传递数据的时候,只能在dragstart中存放数据,在drop事件中获取数据,同时必须得有dragover事件并且必须在dragover事件中添加
event.preventDefault();
box2.addEventListener('dragover',function(){
event.preventDefault();
});
2.对拖动的效果设置的时候
将dataTransfer.effectAllowed = "move"放置到dragstart中表示允许拖动哪种dropEffect;将ev.dataTransfer.dropEffect = "move"放置到dragover中(但是书上写的是放置到dragenter中,但是使用之后没有效果,不知是不是写的不对,才没效果),这只是将拖动的元素设计了一个拖动的效果,最后在drop中将拖动的元素添加到被放置目标中。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <style> div { margin: 0em; padding: 2em; } #source { color: blue; border: 1px solid black; } #target { border: 1px solid black; } </style> <title>Document</title> </head> <body> <div> <p id="source" ondragstart="dragstart_handler(event);" draggable="true"> Select this element, drag it to the Drop Zone and then release the selection to move the element. </p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">Drop Zone</div> <script> function dragstart_handler(ev) { console.log("dragStart: dropEffect = " + ev.dataTransfer.dropEffect + " ; effectAllowed = " + ev.dataTransfer.effectAllowed); ev.dataTransfer.setData("text", ev.target.id); ev.dataTransfer.effectAllowed = "move"; } function drop_handler(ev) { console.log("drop: dropEffect = " + ev.dataTransfer.dropEffect + " ; effectAllowed = " + ev.dataTransfer.effectAllowed); ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); } function dragover_handler(ev) { console.log("dragOver: dropEffect = " + ev.dataTransfer.dropEffect + " ; effectAllowed = " + ev.dataTransfer.effectAllowed); ev.preventDefault(); ev.dataTransfer.dropEffect = "move" } </script> </body> </html>
来源:https://developer.mozilla.org/zh-CN/docs/Web/API/DataTransfer/dropEffect