HTML 5 Drag and drop (Drag and drop), dragdrop

Source: Internet
Author: User

HTML 5 Drag and drop (Drag and drop), dragdrop

Browser support

Internet Explorer 9, Firefox, Opera 12, Chrome, and Safari 5.

1. Set the label draggable attribute to true.

2. added the ondragstart attribute to the tag and called a function drag (Event).

Function drag (ev ){

Ev. dataTransfer. setData ("Text", ev.tar get. id);} // you can specify the data type and value of the dragged data.

3. Add the ondragover attribute to the location (target element) tag to call a function allowDrop (event ).

Function allowDrop (ev ){
Ev. preventDefault ();} // prevents the browser from processing data by default.

4. Add the ondrop attribute to the location (target element) label to be dragged and dropped to call a function drop (event ).

A drop event occurs when data is dragged.

Function drop (ev ){
Ev. preventDefault (); // prevents the browser from processing data by default.
Var data = ev. dataTransfer. getData ("Text"); // obtain the dragged data. This method returns any data set to the same type in the setData () method.
Ev.tar get. appendChild (document. getElementById (data);} // append the dragged element to the target element.

5. Example:

<Script type = "text/javascript">
Function allowDrop (ev ){
Ev. preventDefault ();}

Function drag (ev ){
Ev. dataTransfer. setData ("Text", ev.tar get. id );}

Function drop (ev ){
Ev. preventDefault ();
Var data = ev. dataTransfer. getData ("Text ");
Ev.tar get. appendChild (document. getElementById (data ));}
</Script>

<Div id = "div1" ondrop = "drop (event)" ondragover = "allowDrop (event)">

</Div>
<Div id = "div2" ondrop = "drop (event)" ondragover = "allowDrop (event)"> </div>

Run the following command:

We can drag and drop images back and forth in div1 and div2.

 

Related Article

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.