Hello everyone, I’m Nezha. Nice to meet you ~~

Nezha’s life creed: If you like what you learn, there will be strong motivation to support it.

Learn programming every day, so that you can get a step away from your dream. Thank you for not living up to every programmer who loves programming. No matter how strange the knowledge point is, work with me to calm down the wandering heart and keep going. Welcome to follow me vx:xiaoda0423, welcome to like, favorites and comments

Don’t be afraid to dream, but don’t just dream. Be a doer, not a talker. Vote nezha, thank you for voting for me!! (Nezha)

preface

If this article is helpful to you, ❤️ follow + like ❤️ encourage the author, accept the challenge? Article public account launch, concern programmer Doraemon first time access to the latest article

Ink ❤ ️ ~

knowledge

Before HTML5, you could use mousedown, Mousemove, and Mouseup to implement a clever drag-and-drop operation on a page, but note that the scope of drag-and-drop operation is limited to the browser.

HTML5’s drag and drop API functions directly implement drag and drop operations, and the scope of drag and drop has exceeded the boundaries of the browser, HTML5 provides file API support to drag and drop multiple files and upload.

Learn to master the HTML5 drag-and-drop API and file API, cursor drag-and-drop events, and access local file systems from web pages.

Drag and drop API

Drag-and-drop APIS in HTML5

First, it provides drag-and-drop features for page elements.

Second, added drag-and-drop events for the cursor;

Third, DataTransfer objects are provided for storing drag-and-drop data

Draggable features

The draggable feature defines whether an element allows users to drag and drop: three values are provided

true,false,auto

To make elements drag-and-drop:

<div draggable="true"></div>
Copy the code

Img elements and a elements can be dragged and dropped by default

Cursor drop events

There are seven drag-and-drop cursor events available in HTML5:

In chronological order:

First, the event that is triggered when the drag starts. The event is the dragstart event that is used for the element being dragged

Second, the drag event is triggered during the drag process. The object of the drag event is the element being dragged

Third, the event is emitted when the dragged element enters the scope of the element, and the dragenter element is the element over which the cursor passed during the drag

Fourth, the event is emitted when the dragged element is moving within the scope of the element. The event is the dragover element over which the cursor passed during the dragover

Fifth, the event is emitted when the dragged element is outside the scope of the element. The event is the dragleave element over which the cursor passed during the drag

Sixth, the event is emitted when the dropped element is dropped into the element. The event object is the drop element that is the target element of the drop

Seventh, it is fired at the end of the drag-and-drop operation, and the object of the event is the dragend event

The DataTransfer object

DataTransfer objects are provided in HTML5 to support drag-and-drop data storage.

Implement drag and drop process data exchange.

The DataTransfer object:

attribute

First, the dropEffect property: used to set or get the type of drag action and the type of cursor to display.

If the effect of this operation does not match the effectalhoward effect that was originally set, the drag and drop operation fails. The value can be none, copy, link, or move

Second, the effectalhoward property sets or obtains the source element to which the data transfer operation can be applied to the operation object, specifying the value: None, copy, copyLink, copyMove, Link, linkMove, move, all, and uninitialized

Third, the Type attribute: gets the format of the data stored for the element when the dragstart event starts, or returns Files if it is an external file drag.

Fourth, files property: Get a list of files stored in a DataTransfer object that are being dragged and dropped, FileList, which can be traversed as an array.

methods

First, the clearData() method clears data stored in the DataTransfer object:

clearData([sDataFormat])
Copy the code

[sDataFormat] for optional parameters, the values may be: Text, URL, File, HTML, Image, after setting, can delete specified format of the data, if you omit this parameter, is to remove all the data.

Second, the setData() method adds data in the specified format to an in-memory DataTransfer object:

setData([sDataFormat],[data])
Copy the code

Third, the getData() method: retrieves data from an in-memory DataTransfer object

getData([sDataFormat])
Copy the code

Fourth, the setDragImage() method: sets the image that follows the cursor when dragging and dropping

setDragImage([imgElement],[x],[y])
Copy the code

[imgElement] represents the image object,[x],[y] represents the x-coordinate and y-coordinate relative to the cursor position, respectively

Fifth, the addElement() method: adds elements that are to be dragged along with it. Use this method if you want an element to be dragged along with the dragged element

addElement([element])
Copy the code

[element] represents element objects that are dragged together

The sample

<img SRC ="images/dadaqianduan. PNG "width="50" height="50"> </div> // <div id="dropTarget"></div>Copy the code

Add an onDragStart listener to the drag-and-drop source element and append the contents of the source element to the dataTransfer object when the event is triggered.

Finally, the DragStart() handler that adds the listening event is appended to the window.onload event.

function DragStart() { var source = document.getElementById("dragSource"); // Drag and drop source elements // listen for dragstart events, Source.addeventlistener ("dragstart", function(e){e.datatransfer. setData('text/plain', e.target.innerhtml); / / append data to the dataTransfer object e.d ataTransfer. EffectAllowed = "copy". },false); } // add the function DragStart to window.onload to listen for the event window.addEventListener("load",DragStart,false);Copy the code

Add a dragover listener event, add a dragover listener event to a dragover target element, change the style of the target element when the event is triggered, and mask the browser’s default handling event.

Append the listener handler DragOver() to the window.onload event. For the target element preventDefault(), the browser default must be disabled otherwise drag and drop will not be possible.

Var target = document.getelementById ('dropTarget'); function DragOver() {var target = document.getelementById ('dropTarget'); Target. addEventListener("dragover", function(e){// Change the style this.className = "dragover"; // Cancel the browser's default processing e.preventDefault(); },false); } // add the function DragStart to window.onload to listen for the event window.addEventListener("load", DragOver, false);Copy the code

The onDROP listener event is added to the drag-and-drop target element. The event is triggered to fetch data from the dataTransfer object and append it to the target element, while restoring the style.

Add the listener handler Drop() to the window.onload event.

Var target = document.getelementById ('dropTarget'); function Drop(){var target = document.getelementById ('dropTarget'); Target. addEventListener('drop',function(e){var data = e.datatransfer. getData('text/plain'); This.innerhtml += data; // Get data from dataTransfer. e.dataTransfer.dropEffect = "copy"; // Restore style this.className=""},false); } // add the function DragStart to window.onload to listen for the event window.addEventListener("load",Drop, false);Copy the code

File API

File apis for file manipulation are provided in HTML5, programmatically selecting and accessing file data.

For example, the FileList object, File object, Blob interface, and FileReader interface

Added label features

Multiple and Accept features have been added to form elements of type File in HTML5

Multiple features

The multiple feature allows users to select multiple uploaded files at the same time.

<input type="file" multiple/>
Copy the code

I get a FileList object, which is a list of File objects

The accept features

Specifies the file type that can be submitted through file upload, so that when the file window is opened, the default file type is selected:

<input type="file" accept="image/gif"/>
Copy the code

FileList objects and File objects

Every File in a FileList object is a File object

Example:

<form action="" method="post"> <input type="file" id="files" multiple/> <input type="button" value=" Onclick ="showFiles()"/> <p id=" MSG "></p> </form> function showFiles() {var FileList = document.getElementById("files").files; var msg = document.getElementById("msg"); var file; for(var i=0; i<fileList.length; i++){ file = fileList[i]; msg.innerHTML += file.name + "; <br/>"; }}Copy the code

A Blob object

The Blob object represents raw binary data, and the Blob interface has two attributes: size and Type

First, the size attribute, which represents the length of the Blob object in bytes, can be used

The FileReader interface reads the binary data of a Blob object, or 0 if the Blob object has no bytes

Second, the type attribute, which represents the MIME type of the Blob object, returns an empty string if the type is unknown.

Third, the slice() method is used to slice a file and return a new Blob object.

File objects and Blob objects

File objects inherit from Blob objects, so File objects can also use Blob objects’ properties and methods (File objects can use size and type attributes).

Gets the size and type of the file

Example:

<form action="" method="post"> <input type="file" id="files" multiple accept="image/*"/> <input type="button" Value ="ShowType()" onclick="ShowType()"/> <p id=" MSG "></p> </form> function ShowType(){var files = document.getElementById("files").files; var msg = document.getElementById("msg"); var file; for(var i=0; i<files.length; i++){ file=fileList[i]; MSG. InnerHTML += "length: "+file.size+"; <br/>"; MSG. InnerHTML += "file type: "+file.type+"; <br/>"; }}Copy the code

FileReader interface card

The FileReader interface provides some methods for reading files with an event model that protects the read results.

The FileReader interface reads files into memory and reads the data in the file.

Check in advance to see if your browser supports FileReader

if(typeof FileReader == "undefined"){
 console.log();
} else {
 var reader = new FileReader();
}
Copy the code

The FileReader interface has three attributes:

  1. Returns the status of the read file
  2. data
  3. An error occurred while reading

ReadyState property, read-only

Read the state of the file:

  1. EMPTYP, the value is 0, indicating newFileReaderDefault state when the interface is already built and no read methods are called.
  2. LOADING, with a value of 1, indicating that a file-reading method is reading a File object or Blob object without error.
  3. DONEThe value 2 indicates that the File or Blob has been read completely into memory. An error occurs during the File read, or abort() is used during the read.

The result property is read-only

Gets the file data that has been read. If it is a picture, the base64 format of the picture data is returned.

Error property, read-only

Gets errors that occur while reading files: four types

  1. NotFoundErrorCould not find the resource file to read.

The FileReader interface returns a NotFoundError error and the method that reads the file also raises a NotFoundError error exception

  1. SecurityErrorA security error occurred.

The FileReader interface returns a SecurityError and the method that reads the file also throws a SecurityError exception

  1. NotReadableError, an unreadable error.

The FileReader interface returns a NotReadableError error, and the method that reads the file also raises a NotReadableError exception

  1. EncodingErrorError encoding limit.

It is usually the URL of the data that is limited in length

Method of the FileReader interface

First, the readAsArrayBuffer() method reads the file as an array buffer

readAsArrayBuffer(<blob>);
Copy the code

Where

represents the file of a BLOb object.

The readAsArrayBuffer() method reads the Blob object’s file as an array buffer

Second, the readAsBinaryString() method reads the file as a binary string.

readAsBinaryString(<blob>);
Copy the code

Where

represents the file of a BLOb object.

The readAsBinaryString() method reads the Blob object’s file as a binary string

Third, the readAsText() method reads the file as a binary string

readAsText(<blob>,<encoding>); // Reads as text. Encoding Indicates the encoding of textCopy the code

Fourth, the readAsDataURL() method reads the file as a DataURL string:

readAsDataURL(<blob>); // Read as DataURL stringCopy the code

Fifth, the abort() method breaks the read operation

Abort () // No argumentsCopy the code

Interface events

  1. loadstartEvent, which is triggered when reading data begins
  2. proressEvent, which is triggered when data is being read
  3. loadEvent, which is triggered when the data read completes successfully
  4. abortEvent, which is triggered when an interrupt reads data
  5. errorEvent, which is triggered when an error occurs in reading data
  6. loadendEvent, an event that is triggered when a data read is completed, which may or may not succeed

FileReader interface

Example:

Function ReadAs(action){var blob = document.getelementById ("files").files[0]; var blob = document.getelementById ("files").files[0]; if(blob){ var reader = new FileReader(); / / declare interface method of object / / read the file switch (action) toLowerCase ()) {case "binarystring" : reader. ReadAsBinaryString (blob); break; case "arraybuffer": reader.readAsArrayBuffer(blob); break; case "text": reader.readAsText(blob); break; case "dataurl": reader.readAsDataURL(blob); break; } reader.onload = function(e){var result = this.result; If (/image\/\w+/.test(blob.type) && action.tolowerCase () == "dataurl"){// if(/image\/\w+/.test(blob.type) && action.tolowerCase () == "dataurl"){ document.getElementById("result").innerHTML = "<img src='" + result + "'/>"; } else {document.getelementById ("result").innerhtml = result; }}}}Copy the code

FileReader interface event

Example:

<form action="" method="post"> <input type="file" id="files" multiple accept="image/*"/> <input type="button" Value =" Read file "onclick="FileReaderEvent()"/> <p id="message"></p> </form> var blob = document.getElementById("files").files[0]; var message = document.getElementById("message"); var reader = new FileReader(); Onprogress = function(e){} onprogress = function(e){ Onabort = function(e){} // Add the error event reader. Onerror = Function (e){} // Add loadEnd event reader.onloadEnd = function(e){}Copy the code

Drag the image into the browser

Example:

Define a drop event handler for drop dropHandle()

Define a function loadImg() to load a single file

Var target; Function dropHandle(e){var fileList = e.datatransfer. files, fileType; For (var I =0; i<fileList.length; i++){ fileType = fileList[i].type; if(fileType.indexOf('image') == -1) { alert(''); return; } // load a single file loadImg(fileList[I]); Function loadImg(file){var reader = new FileReader(); Onload = function(e){var oImg = document.createElement("img"); oImg.src = this.result; target.appendChild(oImg); } // Read the file read.readasdataurl (file); }Copy the code

After the page has loaded, you can get the target container, which is used to hold the drag-and-drop image.

Add dragover event handling and drop event handling to the target container

Window.onload = function() {// Get the target element target = document.getelementById ('dropTarget') // Add dragover event to the target element target.addEventListener('dragover', function(e){ e.preventDefault(); },false); target.addEventListener('drop', dropHandle, false); }Copy the code

❤️ follow + like + favorites + comments + forward ❤️, original is not easy, encourage the author to create better articles

Likes, favorites and comments

I’m Jeskson, thanks for your talent: likes, favorites and comments, and we’ll see you next time! ☞ Thank you for learning with me.

See you next time!

This article is constantly updated. You can search “Programmer Doraemon” on wechat to read it for the first time, and reply [information] there are materials of first-line big factories prepared by me, which have been included in this article www.dadaqianduan.cn/#/

Star: github.com/webVueBlog/…