HTML5 Drag and Drop API2

Source: Internet
Author: User

In HTML5, it has been supported to drag data between browsers and other applications, while also greatly simplifying the code for drag and drop.

Steps to implement drag and drop

In HTML5, there are at least two steps to implement a drag-and-drop operation:

    1. Set the Draggable property of the object element you want to drop to True (draggable= "true"). This allows the element to be dragged and dropped. In addition, the IMG element and a element (the href attribute must be specified) are allowed to drag and drop by default.
    2. Write event-handling code related to drag-and-drop. A few events about drag-and-drop exist as shown below.

Related events for drag and drop

Event The element that generated the event Describe
DragStart The element being dragged and dropped. Starts the drag-and-drop operation.
Drag The element being dragged and dropped. During the drag-and-drop process.
DragEnter The element that the mouse passes through during drag and drop. The dragged element begins to enter within the scope of this element.
DragOver The element that the mouse passes through during drag and drop. The dragged element is moving within the scope of this element.
DragLeave The element that the mouse passes through during drag and drop. The dragged element leaves the scope of this element.
Drop The target element to drag and drop. There are other elements that have been dragged and dropped into this element.
Dragend The target element to drag and drop. The drag-and-drop operation ends.

Drag and drop examples for example, for ease of use, add the following function for jquery:

JS Code
  1. JQuery.fn.dragstart = Function (handler) {
  2. return This.each (function () {
  3. This.addeventlistener ("DragStart", Handler, false);
  4. });
  5. };
  6. JQuery.fn.drag = Function (handler) {
  7. return This.each (function () {
  8. This.addeventlistener ("Drag", Handler, false);
  9. });
  10. };
  11. JQuery.fn.dragenter = Function (handler) {
  12. return This.each (function () {
  13. This.addeventlistener ("DragEnter", Handler, false);
  14. });
  15. };
  16. JQuery.fn.dragover = Function (handler) {
  17. return This.each (function () {
  18. This.addeventlistener ("DragOver", Handler, false);
  19. });
  20. };
  21. JQuery.fn.dragleave = Function (handler) {
  22. return This.each (function () {
  23. This.addeventlistener ("DragLeave", Handler, false);
  24. });
  25. };
  26. JQuery.fn.drop = Function (handler) {
  27. var handler1 = Function (event) {
  28. Handler (event);
  29. Event.preventdefault ();
  30. Event.stoppropagation ();
  31. };
  32. return This.each (function () {
  33. This.addeventlistener ("Drop", Handler, false);
  34. });
  35. };
  36. JQuery.fn.dragend = Function (handler) {
  37. var handler1 = Function (event) {
  38. Handler (event);
  39. Event.preventdefault ();
  40. };
  41. return This.each (function () {
  42. This.addeventlistener ("Dragend", Handler, false);
  43. });
  44. };

The sample HTML page code used by the drag-and-drop operation is as follows:

HTML code
  1. <! DOCTYPE HTML>
  2. <html lang= "zh-cn" dir="ltr">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <title> Cast Example </title>
  6. <script type="Text/javascript" src=". /js/jquery-1.6.4.js "></script>
  7. <script type="Text/javascript" src=". /js/dragdrop.js "></script>
  8. </head>
  9. <body>
  10. <H1> Simple drag-and-drop example </H1>
  11.     <div id=< Span class= "Attribute-value" > "Dragme"  draggable= " True " style=" width:200px; border:1px  solid gray;  "> please cast </div >  
  12. <div id="text" style="width:200px; height:200px; border:1px solid Gray; "></div>
  13. </Body>
  14. </html>

The JavaScript code for the drag-and-drop operation is as follows:

JS Code
  1. $ (function () {
  2. $ (document). DragOver (function (event) {
  3. Event.preventdefault ();
  4. });
  5. $ ("#dragme"). DragStart (function (event) {
  6. var dt = Event.datatransfer;
  7. dt.effectallowed = ' all ';
  8. Dt.setdata ("Text/plain", "Hello World");
  9. });
  10. $ ("#text"). Dragend (function (event) {}). Drop (function (event) {
  11. var dt = Event.datatransfer;
  12. var text = dt.getdata ("Text/plain");
  13. $ (this). append (text);
  14. });
  15. });

Code Essentials Description:

  • When you start dragging (the DragStart event occurs), the data you want to drag is stored in the DataTransfer object (SetData () method). The DataTransfer object is designed to hold the data to be carried when dragging and dropping, and it can be set to drag the DataTransfer property of the event object. The first parameter in the SetData () method is a string of data types that carry data, and the second parameter is the data to be carried. The first parameter indicates that the data types in the string can only be populated with words like "text/plain" or "text/html" that represent MIME types, and cannot be filled in with other text.
  • If you put "Dt.setdata (" Text/plain "," Hello World. ")" Instead of "Dt.setdata (" Text/plain ", This.id)", because the ID of the dragged element is taken as an argument, the data that is carried is the data in the dragged element, because the browser automatically reads the data in the element when it reads the data using the GetData () method.
  • For a drag-and-drop target element, you must call the "Event.preventdefault ()" method within the Dragend or DragOver event. Because by default, the target element of the drag and drop is not allowed to accept the element, in order to drag and drop the element into it, the default processing must be closed.
  • After the target element is accepted to the dragged element, the GetData () method is executed to obtain the data from the datatransfer. The parameter of the GetData () method is the type of data specified in the SetData () method.
  • To implement the drag-and-drop process, you must also turn off default processing in the drop event of the target element (deny drag-and-drop), or the target element cannot accept the dragged element.
  • To implement the drag-and-drop process, you must also set the entire page to not perform the default processing (Deny drag-and-drop), or drag-and-drop processing cannot be implemented. Because the page accepts drag-and-drop before other elements, if you reject drag-and-drop on the page, the other elements on the page cannot accept drag-and-drop.
  • To use an element can be dragged and dropped, the element's Draggable property must first be set to true. In addition, in order for this example to work correctly in all browsers that support the drag-and-drop API, you need to specify a WebKit-specific CSS property such as "-webkit-user-drag:element".
  • The kind of data in this example uses the MIME type "Text/plain", or you can drag data from that type into the target element from other applications that use the same MIME type. The types of mime that are now supported for drag processing are: "Text/plain (text text)", "text/html (HTML text)", "Text/xml (XML text)", "Text/uri-list (URL list, one line per URL)".
Properties and methods of DataTransfer objects

If the properties and methods of the DataTransfer object are used well, you can implement a custom drag-and-drop icon that supports only specific drag-and-drop (such as copy, move, and so on) and even more complex drag-and-drop operations:

    • DropEffect Property: Represents the visual effect of a drag-and-drop operation, allowing the setting of its value. The effect must be allowed to specify a value of None, copy, link, move, within the range of the allowed visual effects specified with the Effectallowed property.
    • Effectallowed property: Used to specify the visual effects allowed when an element is dragged and dropped, the values you can specify are: None, copy, Copylink, Copymove, Link, linkmove, move, all, unintialize.
    • Type attribute: A pseudo-array of strings stored in the type of data.
    • void ClearData (domstring format) method: Clears the data stored in the DataTransfer object, and clears the entire data if the argument is omitted.
    • void SetData (domstring format, domstring data) method: Stores the information into the DataTransfer object.
    • Domstring getData (domstring format) method: Reads data from the DataTransfer object.
    • void Setdragimage (element image, long x, long Y) method: Use the IMG element to set the drag-and-drop icon (some browsers can be set with other elements such as canvas).

The SetData () method stores data in the DataTransfer object at the start of a drag-and-drop, uses the Type property to specify the data MIME type, and the GetData () method reads the data from the DataTransfer object at the end of the drag. The ClearData () method can be used to clear data within a DataTransfer object.

Set the visual effect when dragging and dropping

The DropEffect property is combined with the Effectallowed property to set the visual effect when dragging and dropping. The Effectallowed property indicates that the visual effect allowed when an element is dragged is typically set in the Ondragstart event, allowing the set value to be none, copy, Copylink, Copymove, Link, linkmove, move, All, unintialize. The DropEffect property represents the visual effect of the actual drag-and-drop, typically specified in the OnDragOver event, allowing the set value to be none, copy, link, move. The actual visual effect represented by the DropEffect property must be within the range of allowed visual effects represented by the Effectallowed property. The rules are as follows:

    1. If the Effectallowed property is set to None, drag-and-drop elements are not allowed.
    2. If the DropEffect property is not set to none, it is not allowed to be dragged into the target element.
    3. If the Effectallowed property is set to all or not set, the DropEffect property allows to be set to any value and is displayed as a specified visual effect.
    4. If the Effectallowed property is set to a specific effect (not none, all) and the DropEffect property has a specific visual effect, the two specific effect values must be exactly equal, otherwise drag-and-drop elements are not allowed to be dragged into the target element.
JS Code
  1. $ ("#dragme"). DragStart (function (event) {
  2. var dt = Event.datatransfer;
  3. dt.effectallowed = ' copy ';
  4. Dt.setdata ("Text/plain", "Hello.");
  5. });
  6. $ ("#text"). DragOver (function (event) {
  7. var dt = Event.datatransfer;
  8. Dt.dropeffect = ' copy ';
  9. Event.preventdefault ();
  10. });
Custom drag-and-drop icons

In addition to using the Effectallowed property and the DropEffect property above, the HTML5 also allows you to customize the drag-and-drop icon--a small icon located in the lower part of the mouse pointer while dragging an element with the mouse.

The DataTransfer object has a Setdragimage () method that has three parameters, the first parameter image is set to the icon element of the drag-and-drop icon, and the second parameter is the amount of displacement of the drag-and-drop icon from the x-axis direction of the mouse pointer, The third parameter is the amount of displacement of the drag-and-drop icon from the y-axis direction of the mouse pointer.

JS Code
      1. $ (' #dragme '). DragStart (function (event) {
      2. var dt = Event.datatransfer;
      3. Dt.setdragimage (' img '). attr ("src", "images/img1.jpg") [0],-10,-10);
      4. Dt.setdata ("Text/plain", "Welcome");
      5. });

HTML5 Drag-and-drop API2

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.