The main points of knowledge are DataTransfer objects and FileReader (read file information)
1. Create a simple HTML tag:
<body><div id= "box" > Please drag the picture to </div><ul></ul></body>
2. Add a simple style to the label:
<styletype= "Text/css">Div{width:300px;Height:300px;margin:100px;background:Orange;}</style>
3, write JS, use four drag and drop events in 4 target element events
DragEnter Event: Enter the target element trigger, change the DIV's innerHTML value:
var odiv = document.getElementById (' box '), var Oul = document.getElementsByTagName (' ul ') [0];odiv.ondragenter = function () { this.innerhtml = ' can be released ';}
DragOver Event: Enter the target, leave the target, and trigger continuously; Note: Why add this event here? The default event is that you need to block the dragover in order to trigger the drop event:
Odiv.ondragover = function (ev) { ev.preventdefault ();}
Dragleaver event: Off target element trigger
Odiv.ondragleave = function () { this.innerhtml = ' Please drag the picture here ';}
Drop event: Release the mouse trigger on the target element
There is a files property inside the DataTransfer object: Gets the external dragged file, returns a list of Fileslist, and fileslist a type property that returns the types of the file
Odiv.ondrop = function (EV) {
Ev.preventdefault (); var fs = Ev.dataTransfer.files;
Alert (fs.length)//alert (Fs[0].type)
for (var i=0; I<fs. length; i++) { if ( fs[i].type.indexof (' image ')! =-1) { //using the Returned Type property value string contains an image to determine the file typevar fd = newFileReader (); //Read file information Fd.readasdataurl (Fs[i]); //parameter is read file object, read file as DataurlFd.onload= function () { //Touch the OnLoad event when the read file is successfully completed
var oimg = document.createelement (' img '); var oLi = document.createelement (' li '); oimg.src = This.result; Get the data of the file, when the file is a picture, return base64 picture data Oli.appendchild (oimg); Oul.appendchild (oLi); }}else{alert (' Please upload a picture Type! ‘); } } }
HTML5 drag-and-drop event-Upload image Preview function (Learn note)