Drag and drop is a common feature where you grab an object and drag it to another location later. In HTML5, drag and drop is part and any element can be dragged and dropped. Internet Explorer 9, Firefox, Opera 12, Chrome, and Safari 5 support drag and drop.
1.drggable attribute
If the draggable element of a web page element is true, this element can be dragged.
<div draggable="true">Draggable Div</div>
Note: In most browsers, the a element and img element can be dragged and dropped by default, but to be on the safe side, it is best to add the draggable attribute.
2.Event
dragstart: Triggered when the web page element starts to be dragged.
drag: The dragged element continues to fire during the dragging process.
dragenter: Triggered when the dragged element enters the target element. This event should be listened to on the target element.
dragleave: Triggered when the dragged element leaves the target element. This event should be listened to on the target element.
Dragover: Continuously triggered when the dragged element stays in the target element. This event should be listened to on the target element.
drap: The dragged element or the file selected from the file system, triggered when the drag is dropped.
dragend: Triggered when dragging of web element ends.
Note: All of the above events can specify callback functions.
3.dataTransfer object
During the dragging process, the event parameter accepted by the callback function has a dataTransfer attribute. It points to an object and contains various information related to dragging.
draggableElement.addEventListener('dragstart', function(event) { event.dataTransfer.setData('text', 'Hello World!'); });
The above code stores a text message on the dataTransfer object when dragging starts, the content is "Hello World". When the drag and drop ends, you can use the getData method to retrieve this information.
Properties of dataTransfer object:
**dropEffect:** The type of drag-and-drop operation determines how the browser displays the mouse shape. Possible values are copy, move, link, and none.
effectAllowed: Specifies the allowed operations. Possible values are copy, move, link, copyLink, copyMove, linkMove, all, none and uninitialized (the default value is equivalent to all, which means all operations are allowed).
files: Contains a FileList object, representing the files involved in drag and drop. It is mainly used to process files dragged into the browser from the file system.
types: The type of data stored in the DataTransfer object.
Methods of dataTransfer object:
**setData(format, data):** Store data on the dataTransfer object. The first parameter, format, is used to specify the type of data stored, such as text, url, text/html, etc. **getData(format):** Get data from the dataTransfer object. **clearData(format):**Clear the data stored in the dataTransfer object. If the format parameter is specified, only the data in this format will be cleared, otherwise all data will be cleared. **setDragImage(imgElement, x, y):**Specifies the image displayed during dragging. By default, many browsers display a semi-transparent version of the dragged element. The parameter imgElement must be an image element, not a path pointing to the image, and the parameters x and y represent the position of the image relative to the mouse.
The dataTransfer object allows data to be stored on it, which makes it possible to transfer information between the dragged element and the target element.
4.Explanation with examples
1. Drag and drop web page elements
<!DOCTYPE html><html><head> <title>Video step2</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/></head><style>ul{ min-height:100px; background-color:#EEE; margin:20px; }ul li{ background-color:#CCC; padding:10px; margin-bottom:10px; var dragElements = document.querySelectorAll('#drag-elements li'); //Temporarily record the dragged and dropped elements var target = document.querySelector('#drop-target'); //Get the elements that need to be dragged and dropped //Get the target element <ul id="drop-target"></ul><script> </ul> <li draggable= "true">C</li> <li draggable="true">B</li> <li draggable="true">A</li> <ul id="drag-elements"> }</style><body> var elementDragged = null; //Loop to listen for the start and end drag events of the dragged element for (var i = 0; i < dragElements.length; i++) { //Listen for the start drag event dragElements[i]. addEventListener('dragstart', function(e) { //Set the data parameters of the current drag and drop element e.dataTransfer.setData('text', this.innerHTML); //Save the current drag and drop object elementDragged = this; }); //End drag and drop event listening dragElements[i].addEventListener('dragend', function(e) { //Unregister the current drag and drop object elementDragged = null; }); } //The target element listens for the dragged element to enter the event target .addEventListener('dragover', function(e) { //Prevent the browser's default behavior e.preventDefault(); //Set the mouse style e.dataTransfer .dropEffect = 'move'; return false; }); //The target element listens to the event when the dragged element falls. target.addEventListener('drop', function(e) { //Prevent the default behavior e.preventDefault(); //Prevent the default behavior e.stopPropagation(); //Get the storage data parameter of the currently dragged and dropped element this.innerHTML = 'Dropped ' + e.dataTransfer.getData('text'); //Delete the dragged and dropped element document.querySelector('#dragelements'). removeChild(elementDragged); return false; });</script></ body></html>
2. Drag local files
Suppose we want to drag a txt text from the file system and display the content in the browser.
First, obtain the dragged target element and content display area.
var target = document.querySelector('#target');var contentDiv = document.querySelector('#content');
Then, define the dragover event of the target element, mainly to change the mouse shape when the file enters the target element.
target.addEventListener('dragover', function(e) { e.preventDefault(); e.stopPropagation(); e.dataTransfer.dropEffect = 'copy';});
Next, define the drop event of the target element to display the file content.
target.addEventListener('drop', function(e) { e.preventDefault(); e.stopPropagation(); v var fileList = e.dataTransfer.files; if (fileList.length > 0) { var file = fileList[0]; var reader = new FileReader(); reader.end =function(e) { if (e.target.readyState == FileReader.DONE) { var content = reader.result; contentDiv.innerHTML = "File: " + file.name + "\n\n" + content; } } reader.readAsBinaryString(file); } });
Specific code:
<!DOCTYPE html><html><head> <title>Video step2</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/></head> <style>#target{ margin:10px; min-height:100px; max-height:600px; background-color:#EEE; border-radius:5px; overflow:auto; }#content{ padding:10px; font- size :18px; line-height:25px; }</style><body> <div id="target" title="Drag file here"> <div id="content"></div></div> <script> //The target element listens for the event that the dragged and dropped file enters the element area target.addEventListener('dragover', function(e) { //Prevent the default behavior e.preventDefault(); //Prevent the default behavior e.stopPropagation(); //Change the mouse style e.dataTransfer.dropEffect = 'copy'; return false; }); //The target element listens for the event when the dragged and dropped file is dropped target.addEventListener('drop', function(e) { //Prevent the default behavior e.preventDefault(); e.stopPropagation(); //Get all Drag and drop files var fileList = e.dataTransfer.files; if (fileList.length) { //Get the first file var file = fileList[0]; //Create a file input stream var reader = new FileReader(); / /File reading callback function reader.end = function(e) { if (e.target.readyState == FileReader.DONE) { var content = reader.result; contentDiv.innerHTML = 'File: ' + file.name + '\n\n' + content; } } //Read file reader.readAsBinaryString(file); } });</script></body></html>