Home  >  Article  >  Web Front-end  >  Raid on HTML5 Javascript API Extension 4—Drag/Drop Overview_html5 Tutorial Tips

Raid on HTML5 Javascript API Extension 4—Drag/Drop Overview_html5 Tutorial Tips

WBOY
WBOYOriginal
2016-05-16 15:49:591437browse

Drag/Drop is a very common function. You can grab an object and drag it to the area you want to place it. Many javascripts implement similar functions, for example, jQueryUI's draganddrop component. In HTML5, drag and drop has become a standard operation and is supported by any element. Because this feature is so common, all major browsers support this operation.
Enabling the drag-draggable attribute
It is very simple. You only need to change the drag attribute of an element to draggable. This element will support dragging, as shown below:

Copy code
The code is as follows:



Transfer of data during dragging
During the dragging process, we often need to transfer corresponding logical data to complete the conversion process. Here we mainly use the dataTransfer object for data transfer. , let’s take a look at its members:
Method members:

Copy the code
The code is as follows:

setData(format,data): Assign the dragged data to the dataTransfer object.

format: a String parameter that specifies the type of data being dragged. The value of this parameter can be "Text" (text type) and "URL" (URL type). This parameter is case-independent, so passing in "text" and "Text" are the same.
data: A variant type parameter that specifies the dragged data. The data can be text, image paths, URLs, etc.
This function has a Boolean return value. true means that the data is successfully added to dataTransfer, false means unsuccessful. If necessary, you can use this parameter to decide whether certain logic should continue to be executed.

Copy code
The code is as follows:

getData(format): Get the data stored in dataTransfer drag data.

The meaning of format is the same as that in setData, and the value can be "Text" (text type) and "URL" (URL type).

Copy code
The code is as follows:

clearData(format): remove the specified type data.

In addition to the "Text" (text type) and "URL" (URL type) that can be specified above, the format here can also take the following values: file-file, html-html element, image -picture.
This method can be used to selectively process the dragged data type.
Attribute members:

Copy code
The code is as follows:

effectAllowed: Sets or gets the operations that can be performed by the data in the data source element.

The attribute type is string, and the value range is as follows:
"copy"-copy data.
"link"-link data.
"move"-move data
"copyLink"-Copy or link data, determined by the target object.
"copyMove"-Copy or move data, determined by the target object.
"linkMove" - ​​Link or move data, as determined by the target object.
"all"-All operations are supported.
"none"-Disable dragging.
"uninitialized"-Default value, adopt default behavior.
Note that after setting effectAllowed to none, dragging is prohibited, but the mouse shape still displays the shape of no draggable object. If you want to not display this mouse shape, you need to set the attribute returnValue of the window event event to false.

Copy code
The code is as follows:

dropEffect: Set or get the drag target Allowed operations on the .and related mouse shapes.

The attribute type is string, and the value range is as follows:
"copy"-the mouse is displayed as the shape when copied;
"link"-the mouse is displayed as the connected shape;
"move"-The mouse appears as a moving shape.
"none" (default) - The mouse appears as a shape without dragging.
effectAllowed specifies the operations supported by the data source, so it is usually specified in the ondragstart event. dropEffect specifies the operations supported by the drag and drop target, so in conjunction with effectAllowed, it is usually used in ondragenter, ondragover and ondrop events on the drag target.

Copy code
The code is as follows:

files: Returns the list of dragged files FileList.
Types: List of data (draged data) types sent in ondragstart.

The existence of dataTransfer object makes it possible to transfer logical data between the dragged data source and target element. Usually we use the setData method to provide data in the ondragstart event of the data source element, and then use the getData method to obtain the data in the target element.
Events triggered during dragging
The following are the events that will occur during a drag. Basically, the triggering sequence of events is the following sequence:

Copy code
The code is as follows:

dragstart: Triggered when the element to be dragged starts to be dragged. This event object is Drag and drop elements.
drag: Triggered when an element is dragged. This event object is the dragged element.
dragenter: Triggered when a drag element enters the target element. This event object is the target element.
dragover: Triggered when an element is dragged and moved on the target element. This event object is the target element.
dragleave: Triggered when an element is dragged away from the target element. This event object is the target element.
drop: Triggered when the dragged element is placed within the target element. This event object is the target element.
dragend: Triggered after drop, that is, triggered when dragging is completed. This event object is the dragged element.

Basically, the event parameters of the event will be passed in the relevant elements, which can be easily modified. Here, we don't need to handle every event, usually we only need to hook up the main events.
Drag start-ondragstart event
The parameters passed in from this event contain very rich information, from which the dragged element (event.Target) can be easily obtained; You can set the dragged data (event.dataTransfer.setData); so you can easily implement the logic behind dragging (of course you can also pass other parameters when binding).
During the dragging process - ondrag, ondragover, ondragenter and ondragleave events
The object of the ondrag event is the dragged element, and usually this event is handled less frequently. The ondragenter event occurs when the drag enters the current element, the ondragleave event occurs when the drag leaves the current element, and the ondragover event occurs when the drag moves within the current element.
You only need to pay attention to one thing here, because by default, the browser prohibits elements from being dropped, so in order to allow elements to be dropped, you need to return false in this function or call the event.preventDefault() method. As shown in the example below.
Drag end-ondrop, ondragend event
When the draggable data is dropped, the drop event is triggered. After the drop is completed, the dragend event is triggered, and this event is relatively rarely used.
Look at a simple example:

Copy the code
The code is as follows:





functionallowDrop(ev){
ev.preventDefault();
}
functiondrag(ev){
ev.dataTransfer.setData("Text",ev.target.id);
}
functiondrop(ev){
vardata=ev .dataTransfer.getData("Text");
ev.target.appendChild(document.getElementById(data));
ev.preventDefault();
}




< ;imgid="drag1"src="img_logo.gif"draggable="true"ondragstart="drag(event)"width="336"height="69"/>



File dragging
The above example has used various methods and attributes of dataTransfer. Let’s look at another interesting application on the Internet: drag and drop an image to the web page, and then displayed on the web page. This application uses the files attribute of dataTransfer.

Copy code
The code is as follows:


< ;html>


HTML5 Drag and Drop File


< ;body>

Drag your image into the container below:





The files that have been dragged in:


< ulid="list">


<script> <br>if(window.FileReader){ <br>varlist= document.getElementById('list'), <br>cnt=document.getElementById('container'); <br>//Determine whether it is an image <br>functionisImage(type){ <br>switch(type){ <br> case'image/jpeg': <br>case'image/png': <br>case'image/gif': <br>case'image/bmp': <br>case'image/jpg': <br> returntrue; <br>default: <br>returnfalse; <br>} <br>} <br>//Handle the drag and drop file list<br>functionhandleFileSelect(evt){ <br>evt.stopPropagation(); <br> evt.preventDefault(); <br>varfiles=evt.dataTransfer.files; <br>for(vari=0,f;f=files[i];i ){ <br>vart=f.type?f.type :'n/a', <br>reader=newFileReader(), <br>looks=function(f,img){ <br>list.innerHTML ='<li><strong>' f.name '&lt ;/strong>(' t <br>')-' f.size 'bytes<p>' img '</p></li>'; <br>cnt.innerHTML=img; <br>} , <br>isImg=isImage(t), <br>img; <br>//The processed image <br>if(isImg){ <br>reader.onload=(function(theFile){ <br>returnfunction (e){ <br>img='<imgclass="preview"src="' e.target.result '"title="' theFile.name '"/>'; <br>looks(theFile,img ); <br>}; <br>})(f) <br>reader.readAsDataURL(f); <br>}else{ <br>img='"o((>ω<))o", What you sent in is not a picture! ! '; <br>looks(f,img); <br>} <br>} <br>} <br>//Handle the insert and drag effect<br>functionhandleDragEnter(evt){this.setAttribute('style', 'border-style:dashed;');} <br>functionhandleDragLeave(evt){this.setAttribute('style','');} <br>//Handle file drag-in events to prevent browser default events from causing Redirect of <br>functionhandleDragOver(evt){ <br>evt.stopPropagation(); <br>evt.preventDefault(); <br>} <br>cnt.addEventListener('dragenter',handleDragEnter,false); <br>cnt.addEventListener('dragover',handleDragOver,false); <br>cnt.addEventListener('drop',handleFileSelect,false); <br>cnt.addEventListener('dragleave',handleDragLeave,false); <br> }else{ <br>document.getElementById('section').innerHTML='Your browser does not support it, classmate'; <br>} <br></script>



This example uses the file reading API in html5: FileReader object; this object provides the following asynchronous methods for reading files:
1. FileReader.readAsBinaryString(fileBlob)
Read the file in binary mode, the result attribute will contain the binary format of a file
2.FileReader.readAsText(fileBlob,opt_encoding)
Read the file in text mode , the result attribute will contain the text format of a file, and the default decoding parameter is "utf-8".
3.FileReader.readAsDataURL(file)
The result of reading a file in URL form will contain the DataURL format of a file (pictures are usually used this way).
When the file is read using the above method, the following events will be triggered:

Copy the code
The code is as follows:

onloadstart, onprogress, onabort, onerror, onload, onloadend

These events are very simple, just hook them up when needed. Look at the code example below:

Copy the code
The code is as follows:

functionstartRead() {
//obtaininputelementthroughDOM
varfile=document.getElementById('file').files[0];
if(file){
getAsText(file);
}
}
functiongetAsText(readFile){
varreader=newFileReader();
//ReadfileintomemoryasUTF-16
reader.readAsText(readFile,"UTF-16");
//Handleprogress,success, anderrors
reader.onprogress=updateProgress;
reader.onload=loaded;
reader.onerror=errorHandler;
}
functionupdateProgress(evt){
if(evt.lengthComputable){
//evt.loadedandevt.totalareProgressEventproperties
varloaded=(evt.loaded/evt.total);
if(loaded<1){
//Increasetheprogbarlength
//style.width= (loaded*200) "px";
}
}
}
functionloaded(evt){
//Obtainthereadfiledata
varfileString=evt.target.result;
/ /HandleUTF-16filedump
if(utils.regexp.isChinese(fileString)){
//ChineseCharacters Namevalidation
}
else{
//runothercharsettest
}
// xhr.send(fileString)
}
functionerrorHandler(evt){
if(evt.target.error.name=="NotReadableErr"){
//Thefilecouldnotberead
}
}

A brief explanation here: Ordinary file downloads use the window.open method, for example:

Copy code
The code is as follows:

window.open('http://aaa.bbbb.com/ccc.rar','_blank')

Practical reference:
Official documentation: http://www.w3schools.com/html5/
A good tutorial Website: http://html5.phphubei.com/html5/features/DrapAndDrop/
MSDN Help: http://msdn.microsoft.com/en-us/library/ms535861(v=vs.85 ).aspx
File drag and drop details:http://www.html5rocks.com/zh/tutorials/file/dndfiles/
File drag and drop and upload:http://www.chinaz.com/design/2010/0909/131984.shtml
Complete example of file drag and drop upload:http://www.cnblogs.com/liaofeng/archive/ 2011/05/18/2049928.html
Example of file download:http://hi.baidu.com/guo_biru/item/2d7201c012b6debd0c0a7b05
window.open strategy:http://www.cnblogs.com/liulf/archive/2010/03/01/1675511.html
window.open parameters: http://www.koyoz.com/blog /?action=show&id=176
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:HTML5 SVG 2D Introduction 7—Reuse and Reference of SVG Elements_html5 tutorial skillsNext article:HTML5 SVG 2D Introduction 7—Reuse and Reference of SVG Elements_html5 tutorial skills

Related articles

See more