Drag/Drop is a very common feature. You can grab an object and drag it to the area you want to place. Many JavaScripts implement related functions similarly, such as the draganddrop component of jQueryUI. In HTML5, drag drop becomes the standard operation and any element supports it. Because this function is so common, all mainstream browsers support this operation.
Enable drag-draggable propertyIt's very simple. Just modify the drag attribute of an element to draggable, and this element supports dragging, as shown below:
<imgdraggable="true"/>
Passing data while draggingDuring the dragging process, we often need to pass 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 first:
Method members:
setData(format,data): Assign the dragged data to the dataTransfer object.
format: A String parameter that specifies the type of data being dragged. The values of this parameter can be Text (text type) and URL (URL type). This parameter is case-independent, so the text is the same as Text.
data: A variant type parameter that specifies the data being dragged. The data can be text, image path, URL, etc.
This function has a return value of Boolean type. True means that the data is successfully added to the dataTransfer, and false means that it is unsuccessful. If necessary, this parameter can be used to decide whether some logic should be continued.
getData(format): Get the drag data stored in dataTransfer.
format means the same as in setData, and the values can be Text (text type) and URL (URL type).
clearData(format): Removes data of the specified type.
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-image.
This method can be used to selectively process dragged data types.
Attribute members :effectAllowed: Sets or gets the operation that data in the data source element can perform.
The attribute type is a string, and the value range is as follows:
copy-Copy data.
link-link data.
move-mobile 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, determined by the target object.
all-all operations are supported.
none-Drag is prohibited.
uninitialized - default value, adopts default behavior.
Note that after setting effectAllowed to none, dragging is prohibited, but the mouse shape still shows the shape of an object that cannot be dragged. If you want to not display this mouse shape, you need to set the property returnValue of the event event of the window to false.
dropEffect: Sets or gets allowed operations on the dragged target and the associated mouse shape.
The attribute type is a string, and the value range is as follows :copy-The shape of the mouse when it appears as copy;
link-The mouse is shown as the shape of the connection;
move-The mouse appears as a moving shape.
none (default) - The mouse appears as a shape without dragging.
effectAllowed specifies operations supported by the data source, so it is usually specified in the ondragstart event. dropEffect specifies the actions supported by dragging the target, so it is usually used in events such as ondragenter, ondragover and ondrop on the dragged target.
files: Returns the list of dragged files FileList.
types: a list of types of data sent in ondragstart (drag data).
The existence of a dataTransfer object makes it possible to pass logical data between the dragged data source and the target element. Usually we use the setData method to provide data in the ondragstart event of the data source element, and then in the target element, we use the getData method to obtain data.
Events triggered during draggingThe following is the event that will occur when dragging and dropping. Basically, the triggering order of events is the following order:
dragstart: Triggered when the element to be dragged starts to drag. This event object is the dragged element.
drag: Triggered when dragging an element, this event object is the dragged element.
dragenter: Triggered when dragging an element into the target element. This event object is the target element.
dragover: Triggered when dragging an element to move on the target element. This event object is the target element.
dragleave: Triggered when dragging an element away from the target element. This event object is the target element.
drop: Triggered when the dragged element is placed in the target element. This event object is the target element.
dragend: Triggered after drop, which is triggered when the drag is completed. This event object is a dragged element.
Basically, the event parameter event will pass in related elements, which can be easily modified. Here, we do not need to handle each event, we usually only need to hook up a few main events.
Dragstart eventThe parameters passed from this event contain a lot of information, and you can easily obtain the dragged elements (event.Target); you can set the dragged data (event.dataTransfer.setData); so you can easily implement the logic behind the drag (of course, you can also pass other parameters when you bind).
During dragging - ondrag, ondragover, ondragenter and ondragleave events The object of the ondrag event is a drag element, and this event is usually handled less frequently. The ondragenter event occurs when dragging into the current element, the ondragleave event occurs when dragging out of the current element, and the ondragover event occurs when dragging moves in the current element.Just one thing to note here is that by default, the browser prohibits dropping of elements, so in order for elements to drop, you need to return false in this function or call the event.preventDefault() method. As shown in the following example.
Drag end - ondrop, ondragend eventWhen draggable data is dropped, the drop event is triggered. After the drop ends, the dragend event is triggered, and this event is used relatively less.
Let's take a look at a simple example:
<!DOCTYPEHTML>
<html>
<head>
<scripttype="text/javascript">
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();
}
</script>
</head>
<body>
<divid="div1"ondrop="drop(event)"ondragover="allowDrop(event)"></div>
<imgid="drag1"src="img_logo.gif"draggable="true"ondragstart="drag(event)"width="336"height="69"/>
</body>
</html>
Drag and drag fileThe above example has used various methods and properties of dataTransfer. Let’s take a look at another interesting application on the Internet: drag and drop an image on the web page and then display it on the web page. This application uses the files property of dataTransfer.
<!DOCTYPEHTML>
<html>
<head>
<metacharset="utf-8">
<title>HTML5 drag and drop file</title>
<style>
#section{font-family:"Georgia","Microsoft Yahei","Chinese Song";}
.container{display:inline-block;min-height:200px;min-width:360px;color:#f30;padding:30px;border:3pxsolid#ddd;-moz-border-radius:10px;-webkit-border-radius:10px;border-radius:10px;}
.preview{max-width:360px;}
#files-list{position:absolute;top:0;left:500px;}
#list{width:460px;}
#list.preview{max-width:250px;}
#listp{color:#888;font-size:12px;}
#list.green{color:#09c;}
</style>
</head>
<body>
<divid="section">
<p>Drag your image into the container below:</p>
<divid="container"class="container">
</div>
<divid="files-list">
<p>Files that have been dragged in:</p>
<ulid="list"></ul>
</div>
</div>
<script>
if(window.FileReader){
varlist=document.getElementById('list'),
cnt=document.getElementById('container');
//Judge whether the picture is
functionisImage(type){
switch(type){
case'image/jpeg':
case'image/png':
case'image/gif':
case'image/bmp':
case'image/jpg':
returntrue;
default:
returnfalse;
}
}
// Handle drag and drop file list
functionhandleFileSelect(evt){
evt.stopPropagation();
evt.preventDefault();
varfiles=evt.dataTransfer.files;
for(vari=0,f;f=files[i];i++){
vart=f.type?f.type:'n/a',
reader=newFileReader(),
looks=function(f,img){
list.innerHTML+='<li><strong>'+f.name+'</strong>('+t+
')-'+f.size+'bytes<p>'+img+'</p></li>';
cnt.innerHTML=img;
},
isImg=isImage(t),
img;
//Processing the obtained pictures
if(isImg){
reader.onload=(function(theFile){
returnfunction(e){
img='<imgclass="preview"src="'+e.target.result+'"title="'+theFile.name+'"/>';
looks(theFile,img);
};
})(f)
reader.readAsDataURL(f);
}else{
img='"o((>ω<))o", what you sent in is not a picture! ! ';
looks(f,img);
}
}
}
// Handle the insertion and drag out effect
functionhandleDragEnter(evt){this.setAttribute('style','border-style:dashed;');}
functionhandleDragLeave(evt){this.setAttribute('style','');}
// Handle file dragging events to prevent redirection caused by default events of the browser
functionhandleDragOver(evt){
evt.stopPropagation();
evt.preventDefault();
}
cnt.addEventListener('dragenter',handleDragEnter,false);
cnt.addEventListener('dragover',handleDragOver,false);
cnt.addEventListener('drop',handleFileSelect,false);
cnt.addEventListener('dragleave',handleDragLeave,false);
}else{
document.getElementById('section').innerHTML='Your browser does not support it, classmate';
}
</script>
</body>
</html>
In this example, the file reading API in html5 is used: the FileReader object; this object provides the following asynchronous method 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. The default decoding parameter is utf-8.
3.FileReader.readAsDataURL(file)
Reading the file result in URL form will contain the DataURL format of a file (images are usually in this way).
When the file is read using the above method, the following events will be triggered:
onloadstart, onprogress, onabort, onerror, onload, onloadend
These events are very simple, just hook up when needed. See the following code example:
functionstartRead(){
//obtaininputelementthroughDOM
varfile=document.getElementById('file').files[0];
if(file){
getAsText(file);
}
}
functiongetAsText(readFile){
varreader=newFileReader();
//ReadfileintomoryasUTF-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{
//runothercharsettetest
}
//xhr.send(fileString)
}
functionErrorHandler(evt){
if(evt.target.error.name=="NotReadableErr"){
//Thefile could notberead
}
}
Let me briefly talk about it here: ordinary file download uses the window.open method, for example:
window.open('http://aaa.bbbb.com/ccc.rar','_blank')
Practical reference: Official document: http://www.w3schools.com/html5/A good tutorial website: http://html5.phphube.com/html5/features/DrapAndDrop/
MSDN Help: http://msdn.microsoft.com/en-us/library/ms535861(v=vs.85).aspx
Detailed description of file drag and drop: http://www.html5rocks.com/zh/tutorials/file/dndfiles/
Drag and upload the file: http://www.chinaz.com/design/2010/0909/131984.shtml
Complete example of file drag and drop upload: http://www.VeVb.com/liaofeng/archive/2011/05/18/2049928.html
Example of file download: http://hi.baidu.com/guo_biru/item/2d7201c012b6debd0c0a7b05
window.open guide: http://www.VeVb.com/liulf/archive/2010/03/01/1675511.html
window.open parameter: http://www.koyoz.com/blog/?action=show&id=176