↑
Main Page
The dragDrop() method
oEvent.dataTransfer.effectAllowed = “move”;
break;
case “dragenter”:
oEvent.dataTransfer.dropEffect = “move”;
oEvent.returnValue = false;
break;
case “dragover”:
oEvent.returnValue = false;
break;
case “drop”:
oEvent.returnValue = false;
oEvent.srcElement.innerHTML =
oEvent.dataTransfer.getData(“text”);
}
}
</script>
</head>
<body>
<p>Try dragging the text in the textbox to the red square.
The text will be “moved” to the red square.</p>
<p><input type=”text” value=”drag this text”
ondragstart=”handleDragDropEvent(event)” />
<div style=”background-color: red; height: 100px; width: 100px”
ondragenter=”handleDragDropEvent(event)”
ondragover=”handleDragDropEvent(event)”
ondrop=”handleDragDropEvent(event)”></div>
</p>
</body>
</html>
In this example, you can drag text from the text box and drop it onto the red
<div/>
. The text is removed
from the text box because the default behavior of the drop event is overridden. The text is then inserted
into the
<div/>
by using the
innerHTML
property.
If you were to change
dropEffect
and
effectAllowed
to
“copy”
, the text in the text box would
remain and would be duplicated in the
<div/>
.
The dragDrop() method
You already know how to create your own drop targets, so now it’s time to learn about creating your
own draggable items. In IE 5.5, the
dragDrop()
method can be applied to almost any HTML element.
You can initiate a system drag event by calling
dragDrop()
and, therefore, allow normally undraggable
items to fire
dragstart
,
drag
, and
dragend
events.
The trick is to call
dragDrop()
at the correct time. To do this, it is best to use the
onmousemove
event
handler to initiate the drag, like this:
oElement.onmousemove = function (oEvent) {
if (oEvent.button == 1) {
397
Drag and Drop
16_579088 ch13.qxd 3/28/05 11:41 AM Page 397
Free JavaScript Editor
Ajax Editor
©
→