HTML5 Introduction of drag and drop

Source: Internet
Author: User

This article mainly introduces the object and event information related to the drag-and-drop operation, but does not involve too many source code demonstrations.

A simple example

In the HTML5 to implement drag-and-drop operation, relative to the previous implementation through the mouse operation, it is much simpler, data security is more secure. It takes only a few steps to do this.

    1. Adds an attribute to the dragged element draggable , if it is a file drag and drop.
    2. Adding a property to the target element dropzone , which is not required, can be omitted.
    3. Initializes the relevant data information in the dragged element dragstart , primarily the DataTransfer object.
    4. In the event of the target element dragover , its default action is canceled.
    5. In the event of the target element, the data that is drop received is processed.
    6. In the event of being dragged elements dragend , do the aftercare work. If not, you can omit it.

The approximate code is as follows:

<div id= "source" draggable= "draggable" >source</div><div id= "target" >target</div>< Script type= "Text/javascript" >vartarget = document.getElementById (' target '); varSource = document.getElementById (' source '); Source.ondragstart=function(e) {e.datatransfer.effectallowed= ' Copymove '; E.datatransfer.setdata (' Test ', ' TestData ');    }; Target.ondragover=function(e) {E.datatransfer.dropeffect= ' Move '; E.preventdefault (); //Not less
  };
Target.ondrop = function (e) {
var elem = document.createelement (' a ');
elem.innerhtml = e.datatransfer.getdata (' test ');
E.target.appendchild (Elem);
};
</script>

Draggable Property

Draggable is an enumeration property that specifies whether a label can be dragged or not. The following four types of values are available:

    1. true: Indicates that this element can be dragged.
    2. false: Indicates that this element is not draggable.
    3. auto: img the label label href can be dragged and removed, and the a other labels indicate that they cannot be dragged.
    4. Any other value: Indicates not to be dragged.
Dropzone Property

This property is used to accept the target element of the dragged element, indicating the type of data that can be accepted and how it is manipulated. Multiple values are separated by a space and are not case sensitive. The values are composed of the following types:

    • Copy: Indicates that the dragged data is copied to the target element when the allowed element is placed on the element.
    • Link: Indicates that the allowed elements are placed on the element, and the data is linked to the target element.
    • Move: Indicates that the data is moved to the target element when the allowed element is placed on the element.
    • String starting with string : cannot be less than 8 characters long: Represents an object that can accept a DataTransferItem.kind value of string data .
    • A string starting with file: cannot be less than 6 characters long: An object that represents a character that can accept a value of DataTransferItem.kind file that DataTransferItem.type matches a file: DataTransferItem
Related Event Dragevent Interface definition

DragEventInherit from the MouseEvent interface, which is defined as follows, MouseEvent compared to just a few more DataTransfer objects. All actions for dragging are also done by controlling this object.

[Construct (domstring type, optional drageventinit eventinitdict)] interface Dragevent:mouseevent {readonly Attri Bute DataTransfer?datatransfer;};/*This is the parameter definition for the initial event*/dictionary Drageventinit:eventinit {//Properties inherited from Uievent:Window? View =NULL; LongDetail = 0; //Properties inherited from MouseEvent:    LongScreenX = 0; LongScreenY = 0; LongClientX = 0; LongClientY = 0; BooleanCtrlkey =false; BooleanShiftkey =false; BooleanAltkey =false; BooleanMetakey =false; unsigned ShortButton = 0; unsigned Shortbuttons = 0; Eventtarget? Relatedtarget =NULL; //new properties added by Dragevent:DataTransfer?DataTransfer;}

Event description
Dragging related events
Event name Event Target can be undone? Storage mode 1 DropEffect Value Default Action Notes
1. The storage mode is for DataTransfer the object operation, the specific data is shown in the following table.
DragStart Dragged elements Is Read and Write None Initialize operation If you call the Preventdefault () function to cancel the default behavior of this event, the drag function will be canceled.
Drag Dragged elements Is Protection mode None After DragStart, this event is constantly triggered before the mouse is released, regardless of whether the mouse is moving or not.
DragEnter Target element Is Protection mode Effectallowed a qualified value. Replace the target element. Fires once when the target element is entered.
DragLeave The target element before leaving Whether Protection mode None triggered once when leaving.
DragOver Target element Is Protection mode Effectallowed-Qualified value Resets the DropEffect to noneand interrupts subsequent event execution. After DragEnter, this event will not stop until dragleave, regardless of whether it is moved or not.
Drop Target element Is Read-only mode The currently set value When the mouse is released, it is triggered by the target element.
Dragend Dragged elements Whether Protection mode The currently set value After releasing the mouse, it is triggered by the dragged element, in order after the drop.

The target element is the element that the current mouse stays in, such as to drag and drop the a element onto the F element, all the elements passed through in the middle of the mouse Pass, the corresponding event will be triggered, and a element itself is the first target element.

DataTransfer interface

In HTML5, a property is provided for all drag events in order to achieve data exchange during the drag-and-drop process DataTransfer . The method and properties of this object are used to refine the drag-and-drop functionality.

interface DataTransfer {    attribute domstring dropeffect;    Attribute domstring effectallowed;     void Long Long y);    ReadOnly attribute domstring[] types;    Domstring getData (domstring format);     void setData (domstring format, domstring data);     void cleardata (optional domstring format);    readonly attribute datatransferitemlist items;    readonly attribute FileList files;}

Effectallowed and DropEffect

These two properties are used to describe the style of the mouse display during drag and drop, which is affected by the browser and operating system, and the icons displayed by the mouse are not consistent.

effectAllowedIndicates that this drag-and-drop allows the display of the mouse style, which can be the following values:none,copy,copylink,copymove,link, Linkmove,move, all, and uninitialized. This value can only be changed in the dragstart event.

dropEffectRepresents the style displayed during this drag, which can be several values:copy,move,link , and none. In the specific drag process, is also limited by the effectAllowed value, the specific content is shown in the following table, when dropEffect the value is set to a effectAllowed value that is not qualified, the entire chain of events will be aborted, that the subsequent events will not be triggered, but there will be no error prompts.

effectallowed and DropEffect table
effectallowed DropEffect
1: Depending on the platform used by the user, the values that may appear, such as the effectallowed value of Copymove under Windows, default to the copy operation, which becomes a move action when you press the SHIFT key.
None None
Copy Copy
Copylink Copy or Link1
Copymove Copy or Move1
All Copy, Link1, or move1
Link Link
Linkmove Link or move1
Move Move
Uninitialized, dragged into a text box to select the content? Move or Copy1,link1
Uninitialized, is the dragged object a normal selection? Copy or Link1,move1
Uninitialized, dragged object as a linked element a Link or copy1,move1
Other information Copy or Link1,move1
Setdragimage (image, X, y)

This function is used to set the mouse movement along with the mouse movement, rather than the mouse pointer display effect. x, y parameters specify the position of the image relative to the mouse pointer, the image parameter is used to specify the image element, or, if an element, an img image element is displayed, otherwise the given element is converted to an image and displayed.

This function can only be useful in read-write mode ( dragstart that is, event) and is not valid in other events. If you do not call this function, the dragged element is converted to a graph and displayed as a drag.

Items Property

The items interface definition for the pair is as follows:

interface Datatransferitemlist {readonly attribute unsignedLonglength; Getter Datatransferitem (unsignedLongindex); //Items[index]Deletervoid(unsignedLongindex); //Delete Items[index]    voidClear (); Datatransferitem?Add (domstring data, domstring type); Datatransferitem?Add (File data);}    Interface Datatransferitem {readonly attribute domstring kind;    readonly attribute domstring type; voidGetasstring (functionstringcallback?_callback); File?getasfile ();} [Callback, Nointerfaceobject] interface Functionstringcallback {voidhandleevent (domstring data);}

From the definition above it is not difficult DataTransfer.items to see: Is DataTransferItem an array. DataTransferItemListis simply to define a set of interfaces that access objects in an array form DataTransferItem . Let's take a look at DataTransferItem the definition of a class:

    • Kind: Represents the type of data and can only be string or File . It is a good idea to understand what these two values represent.
    • Type: Actual data types or formats, generally expressed in mimetype, but not mandatory mimetype format.
    • Getasstring (callback): When the kind property is string in read-only or read-write mode, the actual data associated with this object can be processed through a callback function.
    • Getasfile (): When kind file Yes, the real data can be obtained through this function, otherwise it will be returned null , only valid in read-only or read-write mode.

When you delete data in non-read-write mode DataTransferItemList , an error is returned InvalidStateError . If you add data in non-read-write mode, no action is taken. DataTransfer.setDatais the encapsulation of the two functions (depending on whether the second parameter is deleted or added).

Types Property

Returns a collection of strings based on the following steps ( DOMStringList ):

    1. Produces an empty DOMStringList object L.
    2. Traverse the DataTransfer.items object.
    3. If the value of the DataTransfer.items subkey kind is string, the value of the item is type added to the L object.
    4. If the DataTransfer.items value of the subkey kind is file, the "Files" string is added to the L object.
    5. Returns an L object
GetData (format)

getDatais to DataTransfer.items find the data from the. Returns data that meets the following criteria:

    1. DataTransferItem.kindAs a string
    2. DataTransferItem.typeThe value equals the format parameter

If no match is found or is in protected mode, an empty string is returned.

Parameters are format converted to lowercase characters before they are passed inside the function, and if the parameter values are text or URLs, they are translated into text/plain and text/ Uri-list.

SetData (format, data)

setDataUsed to DataTransfer.items add or delete a piece of data to:

When you do not specify a second parameter data , data that DataTransfer.items meets the following criteria is removed from:

    1. kindequals string
    2. typeequals parameterformat

When you specify a second parameter data , you DataTransfer.items add data to it, and the newly added data format is as follows:

    1. kindThe value is string
    2. typeThe value isformat
    3. dataDataTransferItemthe actual value of the parameter as.

Parameters are format converted to lowercase characters before they are passed inside the function, and if the parameter values are text or URLs, they are translated into text/plain and text/ Uri-list.

If it is not in read-write mode, no action is made.

ClearData ()

Clears all kind items that have a value of string . Only works in read-write mode.

Storage mode

The storage mode determines DataTransfer whether the content is available. The following table lists the relevant information, where Y is available andN indicates not available.

Read-
DataTransfer The relationship between storage mode and each item
write only protection
DropEffect Only can be changed in the dragenter dragover event, other events can only be read.
Effectallowed Only works in the dragstart event
Items Refer to the following function for the operation details of items setData
Types dragenter dragover drop This value can be obtained only in, with three events
SetData Y N N
GetData Y Y N
ClearData Y N N
Datatransferitem.getasstring Y Y N
Datatransferitem.getasfile Y Y N

From: http://blog.830725.com/post/html5-drag-and-drop-intro.html

HTML5 Introduction of drag and drop

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.