The drag and drop API is a new feature of HTML5. Compared with other new features, it accounts for 60% of the importance and 30% of the usage in actual development. The learning requirements are only enough to master it.
2. What is drag and release?Drag: Drag
Release: Drop
Dragging means that the mouse clicks on the source object and keeps moving the object without letting go. Once let go, it is released.
3. What are source objects and target objects?Source object: refers to a thing that we click with the mouse. It can be a picture, a DIV, a piece of text, etc.
Target object: refers to when we drag the source object and move it to an area. The source object can enter this area, hover over this area (without letting go), and release the source object here (already let go). , you can also leave the area after hovering.
4. Related functions of drag and drop APIAfter explaining what the source object and the target object are, let's return to the drag and drop API in the front end. From the above operations, we can derive several functions
Events that can be triggered by the dragged source object:
(1)ondragstart: The source object starts to be dragged
(2)ondrag: The source object is being dragged (the mouse may or may not be moving)
(3)ondragend: The source object is dragged to the end
Drag the source object to enter the events that can be triggered by the target object above:
(1)ondragenter: The target object is dragged into the source object
(2) ondragover: The target object is dragged by the source object and hovers above it.
(3)ondragleave: The source object is dragged away from the target object
(4)ondrop: Drag the source object and release/let go above the target object
The drag and drop API has a total of 7 functions! !
5. How to transfer data between the dragged source object event and the target object eventHTML5 provides a new attribute for all drag-related events:
e.dataTransfer { } //数据传递对象
Function: Used to pass data between events of the source object and the target object
Save data in an event handler on the source object:
e.dataTransfer.setData( k, v ); //kv必须都是string类型
Read data in an event handler on the target object:
var v = e.dataTransfer.getData(k);
Example 1: Implement a small airplane that can move as the mouse is dragged
Tip: The plane needs to be absolutely positioned! Get the coordinate value of the mouse in the ondrag event! ! !
The code is as follows:
<!DOCTYPE html> <html> <head lang=en> <meta charset=UTF-8> <title></title> <style> body{ margin:0; position: relative; } img{ position:absolute; } </style> </head> <body> <h3>Small plane that moves as the mouse is dragged</h3> <img id=p3 src=img/p3.png <script> p3.ondragstart=function(e){ console.log('Event source p3 starts dragging'); //Record the offset of the mouse on the plane just after dragging offsetX= e.offsetX; offsetY= e. offsetY; } p3.ondrag=function(e){ console.log('Event source p3 is being dragged'); var x= e.pageX; var y= e.pageY; console.log(x+'-'+y); //At the last moment of the drag event, the coordinates of the mouse cannot be read, and both pageX and pageY become 0 if(x==0 && y==0){ return; // Do not handle the situation where both X and Y are 0 at the last moment of dragging} x-=offsetX; y-=offsetY; p3.style.left=x+'px'; p3.style.top=y+'px'; } p3.ondragend=function(){ console.log('Source object p3 drag ends'); } </script> </body> </html>
The effect is as follows:
Example two:
Simulates the effect of a trash can in a computer. A total of three small planes are displayed. After dragging a small plane to the top of the trash can, the small plane is deleted from the DOM tree.
Tip: Deletion requires removing the element from the DOM child node, and the default behavior of ondragover needs to be prevented! ! Use the data transfer between the source object and the target object to record the ID value of the small aircraft! ! !
Important information:
ondragover has a default behavior! ! ! That is when ondragover is triggered, ondrop will fail! ! ! ! This may be a browser version issue, which may only be solved if the browser is continuously updated in the future! !
How to stop it?
ondragover= function(e){ //When the source object is hovering over the target object e.preventDefault(); //Prevent the default behavior so that drop can trigger...}ondrop= function(e){ // The source object is released in the target object...}
The code is as follows:
<!DOCTYPE html> <html> <head lang=en> <meta charset=UTF-8> <title></title> <style> body { text-align: center; } #trash { opacity: .2; margin : 15px; } </style> </head> <body> <h3>Delete child elements from the DOM tree after dragging the plane to the trash can</h3> <img id=trash src=img/trash_full.png> <hr/> <img id=p3 class=src src=img/p3.png> <img id=p4 class=src src=img/p4.png> <img id=p5 class =src src=img/p5.png> <script> //Add event monitoring for the source object - record which source object var was dragged srcList = document.querySelectorAll('.src');//Find all img elements for(var i=0; i<srcList.length; i++){ //Traverse img elements var p = srcList[i]; p.ondragstart = function(e){ //Start dragging the source object e.dataTransfer.setData('PlaneID',this.id); //Save the data--the id of the img element } p.ondrag = function(){} p.ondragend = function(){} } //Add event listening for the target object - delete the dragged source object trash.ondragenter = function(){ //The source object enters the target object console .log('drag enter'); trash.style.opacity = 1; //Change transparency to 1 } trash.ondragleave= function(){ //After the source object leaves the target object, console.log('drag leave') ; trash.style.opacity = .2; //Change transparency to 0.2 } trash.ondragover= function(e){ //The source object is hovering over the target object e.preventDefault(); //Prevent the default behavior, Make drop triggerable} trash.ondrop= function(e){ //The source object is released in the target object console.log('drop'); trash.style.opacity = .2; //Change the transparency to 0.2 //Delete the dragged source object var id = e.dataTransfer.getData('PlaneID'); //Get data--id value var p = document.getElementById(id); //Find related elements based on id value p.parentNode.removeChild(p); //Remove child nodes from parent element} </script> </body> </html>
The effect is as follows:
After dragging the small plane to the trash can to delete:
As shown in the picture, there were originally three small planes, but now there are two! ! !
6. Supplementary knowledge points about drag and drop API! ! (Important, you may be asked during the interview!!)Interview questions:
How to display a picture from the client (computer) in a web page?
How to drag the client's web page to display in the server-side downloaded page?
What do these two questions mean?
We usually drag and drop a picture from the computer to the browser to implement the download operation! ! ! According to the pre-H5 standards, it is impossible to directly drag and drop an image to the browser for display! ! But since the new features of H5 came out, the feature of drag and drop API has been added, which perfectly realizes this function! ! !
Application occasions:
On a certain website, upload a picture as an avatar
Upload photo...
New file operation objects in HTML5:
File: represents a file object
FileList: Represents a file list object, array-like
FileReader: used to read data from files
FileWriter: used to write data to files
Related functions:
div.ondrop = function(e){var f = e.dataTransfer.files[0]; //Find the dragged and dropped file var fr = new FileReader(); //Create a file reader fr.readAsURLData(f); //Read the file content fr.onload = function(){ //Reading completed img.src = fr.result; //Use the read data} }
The code is as follows:
<span style=font-size: 18px;><!DOCTYPE html> <html> <head lang=en> <meta charset=UTF-8> <title></title> <style> #container { border: 1px solid #aaa; border-radius: 3px; padding: 10px; margin: 10px; min-height: 400px; } </style> </head> <body> <h1>Extended knowledge of drag and drop API</h1> <h3>Please drag your photo to the box area below</h3> <div id=container></ div> <script> //Listen to the drop event of document - cancel its default behavior: open the image in a new window document.ondragover = function(e){ e.preventDefault(); //Enable the drop event to be triggered} document.ondrop = function(e){ e.preventDefault(); //Prevent the image from opening in a new window, otherwise the download operation will still be performed! ! ! } //Listen to the drop event of div#container, try to read the released image data, and display it container.ondragover = function(e){ e.preventDefault(); } container.ondrop = function(e){ console.log ('The client dragged a picture and released it...') //The current target object reads the data stored in the drag and drop source object //console.log(e.dataTransfer); //Display a problem //console.log(e.dataTransfer.files.length); //The number of pictures dragged in var f0 = e.dataTransfer.files[0]; //console.log(f0); / /File object File //Read data from the file object var fr = new FileReader(); //fr.readAsText(f0); //Read text string from the file fr.readAsDataURL(f0); //Read URL data from the file fr.onload = function(){ console.log('Reading file completed') console.log(fr.result); var img = new Image(); img.src = fr .result; //URL data container.appendChild(img); } } </script> </body> </html></span>
The effect is as follows:
SummarizeThe above is a detailed explanation of the classic examples of HTML5 drag and drop API introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. I would also like to thank everyone for your support of the VeVb martial arts website!