Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Overview and instance Properties of DataTransfer Interface in JavaScript

2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "Overview and instance properties of DataTransfer interface in JavaScript". In daily operation, I believe many people have doubts about the overview and instance properties of DataTransfer interface in JavaScript. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "Overview and instance properties of DataTransfer interface in JavaScript". Next, please follow the editor to study!

Catalogue

DragEvent interface

Overview of DataTransfer interface

Instance properties of DataTransfer

DataTransfer.dropEffect

DataTransfer.effectAllowed

DataTransfer.files

DataTransfer.types

DataTransfer.items

The example method of DataTransfer

DataTransfer.setData ()

DataTransfer.getData ()

DataTransfer.clearData ()

DataTransfer.setDragImage ()

Drag means that the user holds down the mouse button on an object, drags it to another location, and then releases the mouse button to place the object there.

There are several kinds of objects to drag and drop, including element nodes, pictures, links, selected text, and so on. In a web page, except for element nodes that cannot be dragged by default, others (pictures, links, selected text) can be dragged directly. To make the element node draggable, you can set the draggable attribute of that node to true.

This area can be dragged

The draggable attribute can be used for any element node, but the picture (

) and link () without this attribute, you can drag and drop. For them, when this attribute is used, it is often set to false to prevent dragging these two elements.

Note that once the draggable attribute of an element node is set to true, you can no longer select text or child nodes within that node with the mouse.

Drag events continue to be triggered when the element node or selected text is dragged, including some of the following events.

Drag: continuously triggers (hundreds of milliseconds apart) on the node being dragged during the drag.

Dragstart: when the user starts dragging, it is triggered on the dragged node, and the target attribute of this event is the dragged node. Typically, you should specify the data to be dragged in the listener function for this event.

Dragend: when the drag ends (release the mouse button or press the ESC key), it is triggered on the dragged node, and the target property of this event is the dragged node. It is triggered on the same node as the dragstart event. Regardless of whether the drag is across the window or is canceled halfway, the dragend event is always triggered.

Dragenter: when dragged into the current node, it is triggered once on the current node, and the target attribute of the event is the current node. Typically, you should specify in the listener function for this event whether or not to drop dragged data at the current node. If the current node does not have a listener function for this event, or if the listener function does nothing, it means that data is not allowed to be dropped at the current node. The visual display of dragging into the current node is also set in the listener function for this event.

Dragover: when dragged over the current node, it continues to fire on the current node (hundreds of milliseconds apart), and the target attribute of this event is the current node. The difference between this event and the dragenter event is that the dragenter event is triggered when it enters the node, and then the dragover event continues as long as it does not leave the node.

Dragleave: when a drag operation leaves the scope of the current node, it is triggered on the current node, and the target attribute of the event is the current node. If you want to visually show the drag away from the current node of the operation, set it in the listener function for this event.

Drop: the dragged node or selected text is triggered on the target node when it is released to the target node. Note that if drop is not allowed on the current node, the event will not be triggered even if the mouse button is released over that node. If the user presses the ESC key and cancels the operation, the event will not be triggered. The listener function for this event is responsible for fetching the drag data and processing it.

The following example shows how to dynamically change the background color of the dragged node.

Div.addEventListener ('dragstart', function (e) {this.style.backgroundColor =' red';}, false); div.addEventListener ('dragend', function (e) {this.style.backgroundColor =' green';}, false)

In the above code, when the div node is dragged, the background color changes to red, the drag ends, and then changes back to green.

Here is an example of how to drag a node from the current parent to another parent.

/ * the HTML code is as follows: this node can be dragged * / the dragged node var dragged; document.addEventListener ('dragstart', function (event) {/ / save the dragged node dragged = event.target; / / the background color of the dragged node becomes transparent event.target.style.opacity = 0.5;}, false) Document.addEventListener ('dragend', function (event) {/ / the background color of the dragged node returns to normal event.target.style.opacity =';}, false); document.addEventListener ('dragover', function (event) {/ / prevents the drag effect from being reset, allowing the dragged node to be put into the target node event.preventDefault ();}, false) Document.addEventListener ('dragenter', function (event) {/ / the background color of the target node turns purple / / because the event bubbles, filter the node if (event.target.className =' dropzone') {event.target.style.background = 'purple';}}, false) Document.addEventListener ('dragleave', function (event) {/ / the background color of the target node is restored as is if (event.target.className =' dropzone') {event.target.style.background =';}}, false); document.addEventListener ('drop', function (event) {/ / prevent the default behavior of events (for example, links can be opened on some element nodes), event.preventDefault () If (event.target.className = = 'dropzone') {/ / restore the target node background color event.target.style.background =''; / / insert the dragged node into the target node dragged.removeChild (dragged); event.target.appendChild (dragged);}}, false)

With regard to procrastination, there are a few points to pay attention to.

The drag-and-drop process only triggers these drag events, and although the mouse is moving, the mouse event is not triggered.

Dragging files from the operating system into the browser does not trigger dragstart and dragend events.

Listeners for dragenter and dragover events, which are used to fetch dragged data (that is, allow dragged elements to be dropped). Because most areas of the page are not suitable as target nodes for drop-and-drop elements, the default setting for these two events is that the current node does not allow dragged elements. If you want to drop the data on the target node, you must first block the default behavior of these two events.

In the above code, you cannot drop the dragged node on the div node without canceling the drag event or blocking the default behavior.

DragEvent interface

Drag events all inherit the DragEvent interface, which in turn inherits the MouseEvent interface and the Event interface.

The browser natively provides a DragEvent () constructor to generate an instance object of the drag event.

New DragEvent (type, options)

The DragEvent () constructor accepts two arguments, the first is a string, indicating the type of event, which must be, and the second is the configuration object of the event, which is used to set the properties of the event, which is optional. In addition to accepting the configuration properties of the MouseEvent interface and the Event interface, the configuration object can also set the dataTransfer property to either null or an instance of the DataTransfer interface.

The instance object of DataTransfer is used to read and write data transferred in drag and drop events, as detailed in the section "DataTransfer Interface" below.

Overview of DataTransfer interface

All instances of drag events have a DragEvent.dataTransfer property that reads and writes the data that needs to be passed. The value of this property is an instance of the DataTransfer interface.

The browser natively provides a DataTransfer () constructor that is used to generate DataTransfer instance objects.

Var dataTrans = new DataTransfer ()

The DataTransfer () constructor does not accept arguments.

The procrastinating data is divided into two aspects: the type of data (also known as format) and the value of the data. The type of data is a MIME string (such as text/plain, image/jpeg), and the value of the data is a string. In general, if you drag a piece of text, the data defaults to that text; if you drag a link, the data defaults to the URL of the link.

At the beginning of the drag event, the developer can provide the data type and data value. During the drag-and-drop process, the developer checks the data type through the listeners for dragenter and dragover events to determine whether the dragged object is allowed to be drop. For example, in an area where only drop links are allowed, check that the data type of the drag is text/uri-list.

When the drop event occurs, the listener function takes the dragged data and processes it.

Instance property DataTransfer.dropEffect of DataTransfer

The DataTransfer.dropEffect property is used to set the effect of drop the dragged node, which affects the shape of the mouse as it is dragged over the relevant area. It may take the following values.

Copy: copy the dragged node

Move: move the dragged node

Link: create a link to the dragged node

None: cannot drop the dragged node

Except for the above values, the other values set are invalid.

Target.addEventListener ('dragover', function (e) {e.preventDefault (); e.stopPropagation (); e.dataTransfer.dropEffect =' copy';})

In the above code, once the dragged element drop, the accepted area will copy the node.

The dropEffect property is generally set in the listener functions of dragenter and dragover events, but has no effect on dragstart, drag, and dragleave events. Because this attribute is valid only for areas that accept the dragged node, it is not valid for the dragged node itself. After entering the target area, the drag behavior is initialized to the set effect.

DataTransfer.effectAllowed

The DataTransfer.effectAllowed property sets the effect allowed in this drag. It may take the following values.

Copy: copy the dragged node

Move: move the dragged node link: create a link to the dragged node

CopyLink: allow copy or link

CopyMove: allow copy or move

LinkMove: allow link or move

All: allow all effects

None: cannot drop the dragged node

Uninitialized: default value, equivalent to all

If an effect is not allowed, the user will not be able to achieve it in the target node.

This property and the dropEffect property are two aspects of the same thing. The former sets the effect allowed by the dragged node, while the latter sets the effect of the area that accepts the drag, and they are often used together.

The listener function for the dragstart event, which can be used to set this property. It is not valid to set this property in the listener function of other events.

Source.addEventListener ('dragstart', function (e) {e.dataTransfer.effectAllowed =' move';}); target.addEventListener ('dragover', function (e) {ev.dataTransfer.dropEffect =' move';})

As long as one of the dropEffect and effectAllowed attributes is none, the drop operation cannot be completed on the target node.

DataTransfer.files

The DataTransfer.files property is a FileList object that contains a set of local files that can be used to transfer during a drag-and-drop operation. If the drag does not involve a file, the property is an empty FileList object.

Here is an example of receiving drag-and-drop files.

/ / the HTML code is as follows: / / var div = document.getElementById ('output'); div.addEventListener ("dragenter", function (event) {div.textContent ='; event.stopPropagation (); event.preventDefault ();}, false); div.addEventListener ("dragover", function (event) {event.stopPropagation (); event.preventDefault ();}, false); div.addEventListener ("drop", function (event) {event.stopPropagation ()) Event.preventDefault (); var files = event.dataTransfer.files; for (var I = 0; I

< files.length; i++) { div.textContent += files[i].name + ' ' + files[i].size + '字节\n'; }}, false); 上面代码中,通过dataTransfer.files属性读取被拖拉的文件的信息。如果想要读取文件内容,就要使用FileReader对象。 div.addEventListener('drop', function(e) { e.preventDefault(); e.stopPropagation(); var fileList = e.dataTransfer.files; if (fileList.length >

0) {var file = fileList [0]; var reader = new FileReader (); reader.onloadend = function (e) {if (e.target.readyState = FileReader.DONE) {var content = reader.result; div [XSS _ clean] = 'File:' + file.name +'\ n\ n' + content;}} reader.readAsBinaryString (file);}}); DataTransfer.types

The DataTransfer.types attribute is a read-only array, with each member being a string with a drag-and-drop data format (usually a MIME value). For example, if you are dragging text, the corresponding member is text/plain.

The following is an example that determines whether drop operations are allowed on the current node by checking the type of the dataTransfer attribute.

Function contains (list, value) {for (var I = 0; I < list.length; + + I) {if (list [I] = = value) return true;} return false;} function doDragOver (event) {var isLink = contains (event.dataTransfer.types, 'text/uri-list'); if (isLink) event.preventDefault ();}

In the above code, drop at the current node is allowed only if the dragged node is a link.

DataTransfer.items

The DataTransfer.items property returns an array-like read-only object (DataTransferItemList instance), and each member is an object (DataTransferItem instance) of this drag. If the drag does not contain an object, an empty object is returned.

The DataTransferItemList instance has the following properties and methods.

Length: returns the number of members

Add (data, type): add a string of specified content and type (such as text/html and text/plain) as a member

Add (file): another use of the add method to add a file as a member

Remove (index): removes a member from a specified location

Clear (): remove all members

The DataTransferItem instance has the following properties and methods.

Kind: returns the type of member (string or file).

Type: returns the type of the member (usually the MIME value).

GetAsFile (): if the dragged file is a file, return the file, otherwise return null.

GetAsString (callback): if the character being dragged is a string, pass the character into the specified callback function for processing. This method is asynchronous, so you need to pass in a callback function.

Here is an example.

Div.addEventListener ('drop', function (e) {e.preventDefault (); if (e.dataTransfer.items! = null) {for (var I = 0; I < e.dataTransfer.items.samples; items +) {console.log (e.dataTransfer.items [I] .kind +:' + e.dataTransfer.items [.type];}}); the instance method DataTransfer.setData () of DataTransfer

The DataTransfer.setData () method is used to set the data that comes with the drag event. The method does not return a value.

Event.dataTransfer.setData ('text/plain',' Text to drag')

The above code adds plain text data to the current drag event.

This method accepts two parameters, both of which are strings. The first parameter represents the data type (such as text/plain), and the second parameter is the specific data. If the specified type of data does not exist in the dataTransfer property, then the data will be added, otherwise the original data will be replaced with the new data.

If you drag the text box or drag the selected text, the corresponding text data will be added to the dataTransfer attribute by default, without having to specify it manually.

Aaa

In the above code, dragging this element automatically carries the text data aaa.

Using the setData method, you can replace the original data.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report