Comments: Call preventDefault () to prevent the browser from processing data by default (the default action of the drop event is opened in the form of a link) through dataTransfer. the getData (Text) method obtains the dragged data. If you are interested, refer
Original Effect
Effect After dragging
The Code is as follows:
The Code is as follows:
[Code]
<! Doctype html>
<Html>
<Head>
<Style type = "text/css">
# Div1, # div2
{Float: left; width: 100px; height: 35px; margin: 10px; padding: 10px; border: 1px solid # aaaaaa ;}
</Style>
<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>
</Head>
<Body>
<Div id = "div1" ondrop = "drop (event)" ondragover = "allowDrop (event)">
</Div>
<Div id = "div2" ondrop = "drop (event)" ondragover = "allowDrop (event)"> </div>
</Body>
</Html>
[/Code]
It may seem a little complicated, but we can study the different parts of drag-and-drop events separately.
Set the element to drag and drop
First, set the draggable attribute to true to make the element drag:
The Code is as follows:
Drag-ondragstart and setData ()
Then, specify what will happen when the element is dragged.
In the preceding example, the ondragstart attribute calls a function (Event), Which specifies the data to be dragged.
The dataTransfer. setData () method sets the data type and value of the dragged data:
The Code is as follows:
Function drag (ev)
{
Ev. dataTransfer. setData ("Text", ev.tar get. id );
}
In this example, the data type is "Text", and the value is the id ("drag1") of the element that can be dragged ").
Where to put-ondragover
The ondragover event specifies where to place the dragged data.
By default, data/elements cannot be placed in other elements. To allow placement, We must block the default Processing Method for elements.
You must call the ondragover eventEvent. PreventDefault () method:
The Code is as follows:
Event. preventDefault ()
Place-ondrop
A drop event occurs when data is dragged.
In the preceding example, the ondrop attribute calls a function (Event):
The Code is as follows:
Function drop (ev)
{
Ev. preventDefault ();
Var data = ev. dataTransfer. getData ("Text ");
Ev.tar get. appendChild (document. getElementById (data ));
}
Code explanation:
PreventDefault () is called to prevent the browser from processing data by default (the default action of the drop event is opened in the form of a link). The dragged data is obtained through the dataTransfer. getData ("Text") method. This method returns any data set to the same type in the setData () method. The dragged data is the id of the dragged element ("drag1"). It is appended to the placed element (the target element ).