Drag and drop
Drag and drop is a common feature, which is to grab an object and drag it to another location later.
In HTML5, drag and drop is part of the standard, and any element can be dragged and dropped.
1. HTML5 Drag and Drop
Drag and drop (Drag and drop) are part of the HTML5 standard.
2. Drag start
ondragstart: A function is called, drag (event), which specifies the data to be dragged
3. Set drag data
setData(): Set the data type and value of the dragged data.
4. Placement into position
ondragover: The event specifies where to place the dragged data.
5. Placement
ondrop: When placing the dragged and dropped data, a drop event will occur
Summary:
ondrop Events triggered on the drag target (source element):
ondragstart: Triggered when the user starts dragging the element
ondrag: Triggered when the element is being dragged
ondragend: Triggered after the user completes dragging the element
Events triggered when the target is released
ondragenter: This event is triggered when the object dragged by the mouse enters its container scope
ondragover: When a dragged object is in another object container This event is triggered when dragging within the range
ondragleave: This event is triggered when the object being dragged by the mouse leaves the range of its container
ondrop: This event is triggered when the mouse button is released during a dragging process
Drag and drop example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>drop</title> <style> .box{ width: 400px; height: 400px; } #box1{ float: left; background-color: #CCCCCC; } #box2{ float: left; background-color: aqua; } </style> <script> var box1Div, msgDiv, img1, box2Dib; window.onload = function () { box1Div = document.getElementById("box1"); msgDiv = document.getElementById("msg"); img1 = document.getElementById("img1"); box2Div = document.getElementById("box2"); box1Div.ondragover = function (e) { e.preventDefault(); } box2Div.ondragover = function (e) { e.preventDefault(); } img1.ondragstart = function (e) { e.dataTransfer.setData("imgId","img1"); } box1Div.ondrop = dropImghandler; box2Div.ondrop = dropImghandler; function dropImghandler(e) { //创建节点 var img = document.getElementById(e.dataTransfer.getData("imgId")); e.target.appendChild(img); } } function showObj(obj) { var s = ""; for(var k in obj){ s+=k+":"+obj[k]+"<br/>"; } msgDiv.innerHTML = s; }</script> </head> <body> <div id="box1" class="box"></div> <div id="box2" class="box"></div> <img id="img1" src="http://img4.imgtn.bdimg.com/it/u=4240085321,3307603809&fm=21&gp=0.jpg" alt=""> <div id="msg"></div> </body> </html>