In web development, if we want to achieve the drag-and-drop effect, we need to use Javascript. Today let us use Html5 to implement it:
Look at the html core code first:
Drag the small yellow square into the big red box
The draggable attribute is newly added in HTML5. It has three values: true, false, and auto. True means draggable, false means not possible. Auto depends on whether the user's browser supports it. For more information, please refer to the official documentation.
Add a little style:
Then let’s look at javascript:
function listenEvent(eventTarget, eventType, eventHandler) {
if (eventTarget .addEventListener) {
eventTarget.addEventListener(eventType, eventHandler,false);
} else if (eventTarget.attachEvent) {
eventType = "on" eventType;
eventTarget.attachEvent(eventType, eventHandler );
} else {
eventTarget["on" eventType] = eventHandler;
}
}
// cancel event
function cancelEvent (event) {
if ( event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
}
// cancel propagation
function cancelPropagation ( event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
}
window. onload=function() {
var target = document.getElementById("drop");
listenEvent(target,"dragenter",cancelEvent);
listenEvent(target,"dragover", dragOver);
listenEvent(target,"drop",function (evt) {
cancelPropagation(evt);
evt = evt || window.event;
evt.dataTransfer.dropEffect = 'copy';
var id = evt.dataTransfer.getData("Text");
target.appendChild(document.getElementById(id));
});
var item = document.getElementById("item") ;
item.setAttribute("draggable", "true");
listenEvent(item,"dragstart", function(evt) {
evt = evt || window.event;
evt. dataTransfer.effectAllowed = 'copy';
evt.dataTransfer.setData("Text",item.id);
});
};
function dragOver(evt) {
if (evt.preventDefault) evt.preventDefault();
evt = evt || window.event;
evt.dataTransfer.dropEffect = 'copy';
return false;
}
From the above code, we see the use of a set of drag and drop Events provided by HTML5. Let’s look directly at the following:
dragstart
Drag event starts.
drag
During the drag operation.
dragenter
Drag is over the target; used to determine if target will accept drop.
dragover
Drag is over target; used to determine feedback to user.
drop
Drop occurs.
dragleave
Drag leaves target.
dragend
Drag operation ends.
defines related events to achieve the desired function. The above Js is not difficult to understand.
You can try it yourself. Opera currently has the best support, but IE does not work well.
Hope it will be helpful to your web development.