Simple drag and drop in the HTML5
Drag-and-drop is a common feature that grabs an object and then drags it to another location. In HTML5, drag-and-drop is part of the standard, and any element can be dragged and dropped.
In order for the element to be draggable, you need to use the HTML5 Draggable property to set its value to true. Links, text and pictures are draggable by default (text can be dragged in the selected state, links and pictures can be dragged under any circumstances), and no draggable properties are required.
<!DOCTYPE HTML><HTML><HeadLang= "en"> <MetaCharSet= "UTF-8"> <title></title> <styletype= "Text/css">Div{Border:1px solid Red;Height:300px; } </style></Head><Body> <DivID= "Dropblock"></Div> <imgsrc=".. /image/2page-img1.jpg "ID= "IMGs"/><BR/></Body><Script> varIMGs=document.getElementById ("IMGs"); Imgs.ondragstart=function(e) {e.datatransfer.setdata ("Text", e.target.id); } varDiv=document.getElementById ("Dropblock"); Div.ondragover=function(e) {e.preventdefault (); } Div.ondrop=function(e) {e.preventdefault (); varData=E.datatransfer.getdata ("Text"); E.target.appendchild (document.getElementById (data))}</Script></HTML>
Drag what?
The dragged picture is first bound to a ondragstart event, which specifies the data being dragged.
The Datatransfer.setdata () method sets the data type and value of the dragged data:
E.datatransfer.setdata ("Text", e.target.id);
In this example, the data type is "Text" and the value is the ID of the draggable element ("IMGs").
Where to put it?
A OnDragOver event is bound for the drop zone (ID dropblock), which specifies where to place the dragged data.
By default, data/elements cannot be placed in other elements. If you need to set allow placement, we must block the default handling of elements.
This is done by invoking the event for OnDragOver events. Preventdefault () Method:
For placement
A OnDrop event is bound for the drop zone (ID dropblock), which occurs when the data is dropped.
The event executes the following code:
Div.ondrop=function (e) { e.preventdefault (); var data= e.datatransfer.getdata ("Text"); E.target.appendchild (document.getElementById (data)) }
Code Explanation:
- Call Preventdefault () to avoid browser default handling of data (the default behavior of the drop event is to open as a link)
- The dragged data is obtained by means of the Datatransfer.getdata ("Text") method. The method returns any data that is set to the same type in the SetData () method.
- The dragged data is the ID of the dragged element ("IMGs")
- Appends the dragged element to the placement element (the target element)
Simple drag and drop in the HTML5