Raid HTML5 JavascriptAPI extension 4-Drag (Drag/Drop) Overview _ html5 tutorial skills-

Source: Internet
Author: User
DragDrop is a very common function. You can capture an object and drag it to the area you want to place it. In HTML5, draganddrop becomes a standard operation, all elements are supported. Because this function is too common, all mainstream browsers support this operation. If you are interested, you may find it helpful to Drag (Drag/Drop) is a very common function. You can capture an object and drag it to the desired area. Many javascript Functions are similar, such as the draganddrop component of jQueryUI. In HTML5, draganddrop becomes a standard operation and is supported by any element. Because this function is too common, all mainstream browsers support this operation.
Enable the drag-draggable attribute
It is very simple. You only need to change the drag attribute of an element to draggable. This element supports dragging, as shown below:

The Code is as follows:




Data transmission during dragging
During the drag process, we often need to pass the corresponding logical data to complete the conversion process. Here we mainly use the dataTransfer object for data transmission. Let's first look at its members:
Method member:

The Code is as follows:


SetData (format, data): Assign the dragged data to the dataTransfer object.


Format: A String parameter that specifies the type of the dragged data. This parameter can be set to "Text" or "URL ). This parameter is case-insensitive, so "text" is the same as "Text.
Data: A variant type parameter that specifies the dragged data. The data can be text, image path, URL, and so on.
This function has a return value of the Boolean type. true indicates that the data is successfully added to the ranransfer. false indicates that the data is not successful. If necessary, you can use this parameter to determine whether to continue executing certain logic.

The Code is as follows:


GetData (format): Get the drag data stored in dataTransfer.


The format value is the same as that in setData. The value can be "Text" or "URL ).

The Code is as follows:


ClearData (format): Remove Data of the specified type.


In addition to the preceding "Text" (Text type) and "URL" (URL type), the format can also take the following values: file-file, html-html element, image-image.
This method can be used to selectively process the dragged data type.
Attribute Member:

The Code is as follows:


EffectAllowed: sets or obtains operations that can be performed on data in the data source element.


The property type is a string and the value range is as follows:
"Copy"-copy data.
"Link"-link data.
"Move"-move data
"CopyLink"-copy or link data, determined by the target object.
"CopyMove"-copy or move data, determined by the target object.
"LinkMove"-link or move data, determined by the target object.
"All"-all operations are supported.
"None"-drag prohibited.
"Uninitialized"-default value, default behavior.
Note that if you set the direction tallowed to none, dragging is forbidden, but the Mouse shape still shows the shape of the object without dragging. If you want to not display this mouse shape, you need to set the returnValue attribute of the event of the window to false.

The Code is as follows:


DropEffect: set or obtain the operations and mouse shapes allowed on the dragged target.


The property type is a string and the value range is as follows::
"Copy"-the mouse is displayed as the copy shape;
"Link"-The mouse shows the connection shape;
"Move"-the mouse is displayed as a moving shape.
"None" (default)-The mouse is displayed as a shape without dragging.
EffectAllowed specifies the operations supported by the data source, so it is usually specified in the ondragstart event. DropEffect specifies the operations supported by the target to be dragged and placed. Therefore, it is usually used in events such as ondragenter, ondragover, and ondrop on the target to be dragged.

The Code is as follows:


Files: returns the list of dragged files FileList.
Types: List of Data types sent in ondragstart (dragged data.


The existence of a dataTransfer object makes it possible to transmit logical data between the dragged data source and the target element. Generally, we use the setData method to provide data in the ondragstart event of the data source element, and then use the getData method to obtain data in the target element.
Events triggered by dragging
The following is an event that occurs during a drag operation. Basically, the trigger sequence of the event is as follows:

The Code is as follows:


Dragstart: triggered when the element to be dragged starts to be dragged. This event object is a drag element.
Drag: triggered when an element is dragged. This event object is a drag element.
Dragenter: triggered when the drag element enters the target element. This event object is the target element.
Dragover: triggered when an element is dragged to move on the target element. The event object is the target element.
Dragleave: triggered when an element is dragged out of the target element. The event object is the target element.
Drop: triggered when the dragged element is placed in the target element. This event object is the target element.
Dragend: triggered after the drop operation. It is triggered when the drag operation is complete. This event object is a drag element.


Basically, the event parameter event will pass in related elements, which can be easily modified. Here, we do not need to handle every event. Generally, we only need to hook up the main events.
Drag start-ondragstart event
Parameters passed in from this event contain a wealth of information, from which you can easily obtain the dragged element (event. target); from which you can set the data to be dragged (event. dataTransfer. setData); so you can easily implement the logic behind the drag (of course, you can also pass other parameters when binding ).
-Ondrag, ondragover, ondragenter, and ondragleave events during dragging
The object of an ondrag event is a drag-and-drop element. Generally, this event is rarely processed. The ondragenter event occurs when you drag the current element. The ondragleave event occurs when you drag the current element, and the ondragover event occurs when you drag the current element.
Note that, by default, the browser disables element drop. To allow the element to be dropped, you must return false or call the event in this function. preventDefault () method. The following is an example.
Drag end-ondrop, ondragend event
The drop event is triggered when the data that can be dragged is dropped. After the drop event ends, the dragend event is triggered, and this event is rarely used.
Let's look at a simple example:

The Code is as follows:






FunctionallowDrop (ev ){
Ev. preventDefault ();
}
Functiondrag (ev ){
Ev. dataTransfer. setData ("Text", ev.tar get. id );
}
Functiondrop (ev ){
Vardata = ev. dataTransfer. getData ("Text ");
Ev.tar get. appendChild (document. getElementById (data ));
Ev. preventDefault ();
}
Script







Drag
The preceding example uses the methods and attributes of dataTransfer. Next, let's look at another interesting online application: drag an image to a webpage and display it on the webpage. This application uses the files attribute of dataTransfer.

The Code is as follows:






HTML5 drag-and-drop files




Drag your image to the container below:





Files dragged in:





Script
If (window. FileReader ){
Varlist = document. getElementById ('LIST '),
Cnt = document. getElementById ('Container ');
// Determine whether the image is used
FunctionisImage (type ){
Switch (type ){
Case 'image/jpeg ':
Case 'image/png ':
Case 'image/gif ':
Case 'image/bmp ':
Case 'image/jpg ':
Returntrue;
Default:
Returnfalse;
}
}
// Process the drag-and-drop file list
FunctionhandleFileSelect (evt ){
Evt. stopPropagation ();
Evt. preventDefault ();
Varfiles = evt. dataTransfer. files;
For (vari = 0, f; f = files [I]; I ++ ){
Vart = f. type? F. type: 'n'/',
Reader = newFileReader (),
Looks = function (f, img ){
List. innerHTML + ='
  • '+ F. name +'('+ T +
    ')-' + F. size + 'bytes

    '+ Img +'

  • ';
    Cnt. innerHTML = img;
    },
    IsImg = isImage (t ),
    Img;
    // Processed image
    If (isImg ){
    Reader. onload = (function (theFile ){
    Returnfunction (e ){
    Img = '';
    Looks (theFile, img );
    };
    }) (F)
    Reader. readAsDataURL (f );
    } Else {
    Img = '"o (> ω <) o", it's not an image you passed in !! ';
    Looks (f, img );
    }
    }
    }
    // Process insert and drag results
    FunctionhandleDragEnter (evt) {this. setAttribute ('style', 'border-style: dashed ;');}
    FunctionhandleDragLeave (evt) {this. setAttribute ('style ','');}
    // Process file drag events to prevent redirection caused by browser default events
    FunctionhandleDragOver (evt ){
    Evt. stopPropagation ();
    Evt. preventDefault ();
    }
    Cnt. addEventListener ('dragenter', handleDragEnter, false );
    Cnt. addEventListener ('dragover', handleDragOver, false );
    Cnt. addEventListener ('drop', handleFileSelect, false );
    Cnt. addEventListener ('dragleave ', handleDragLeave, false );
    } Else {
    Document. getElementById ('core'). innerHTML = 'unsupported by your browser, studen ';
    }
    Script



    In this example, the file reading API in html5 is used: FileReader object, which provides the following asynchronous methods for reading files:
    1. FileReader. readAsBinaryString (fileBlob)
    Read files in binary format. The result attribute contains the binary format of a file.
    2. FileReader. readAsText (fileBlob, opt_encoding)
    When a file is read as text, the result attribute will contain the text format of the file. The default decoding parameter is "UTF-8 ".
    3. FileReader. readAsDataURL (file)
    Reading a file result as a URL will contain the DataURL format of a file (this is usually used for images ).
    When the preceding method is used to read files, the following events are triggered:

    The Code is as follows:


    Onloadstart, onprogress, onabort, onerror, onload, onloadend


    All these events are simple. You can mount them when necessary. See the following code example:

    The Code is as follows:


    FunctionstartRead (){
    // ObtaininputelementthroughDOM
    Varfile = document. getElementById ('file'). files [0];
    If (file ){
    GetAsText (file );
    }
    }
    FunctiongetAsText (readFile ){
    Varreader = newFileReader ();
    // ReadfileintomemoryasUTF-16
    Reader. readAsText (readFile, "UTF-16 ");
    // Handleprogress, success, andrors
    Reader. onprogress = updateProgress;
    Reader. onload = loaded;
    Reader. onerror = errorHandler;
    }
    FunctionupdateProgress (evt ){
    If (evt. lengthComputable ){
    // Evt. loadedandevt. totalareProgressEventproperties
    Varloaded = (evt. loaded/evt. total );
    If (loaded <1 ){
    // Increasetheprogbarlength
    // Style. width = (loaded * 200) + "px ";
    }
    }
    }
    Functionloaded (evt ){
    // Obtainthereadfiledata
    Varfilestringincluevt.tar get. result;
    // HandleUTF-16filedump
    If (utils. regexp. isChinese (fileString )){
    // ChineseCharacters + Namevalidation
    }
    Else {
    // Runothercharsettest
    }
    // Xhr. send (fileString)
    }
    FunctionerrorHandler (evt ){
    If(evt.tar get. error. name = "NotReadableErr "){
    // Thefilecouldnotberead
    }
    }


    The window. open method is used for normal file download. For example:

    The Code is as follows:


    Window. open ('HTTP: // aaa.bbbb.com/ccc.rar', '_blank ')


    Practical reference:
    Official documents: http://www.w3schools.com/html5/
    A good tutorial Website: http://html5.phphubei.com/html5/features/DrapAndDrop/
    MSDN help: http://msdn.microsoft.com/en-us/library/ms535861 (v = vs.85). aspx
    Drag details: http://www.html5rocks.com/zh/tutorials/file/dndfiles/
    Drag and Drop files and upload: http://www.chinaz.com/design/2010/0909/131984.shtml
    Complete example of Drag and Drop File Upload: http://www.cnblogs.com/liaofeng/archive/2011/05/18/2049928.html
    Example of File Download: http://hi.baidu.com/guo_biru/item/2d7201c012b6debd0c0a7b05
    Window. open Introduction: http://www.cnblogs.com/liulf/archive/2010/03/01/1675511.html
    Window. open parameter: http://www.koyoz.com/blog? Action = show & id = 176

    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.