每天一个JavaScript实例-html5拖拽

时间:2023-03-11 12:52:37
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>每天一个JavaScript实例-html5拖拽</title>
<style>
#drop{
width:300px;
height:200px;
background-color:#f00;
padding:5px;
border:2px solid #000;
}
#item{
width:100px;
height:100px;
background-color:#ff0;
padding:5px;
margin:20px;
border:1px solid #000;
}
*[draggable=true]{
-moz-user-select:none;
-khtml-user-drag:element;
cursor:move;
}
*:-khtml-drag{
background-color:rgba(238,238,238,0.5);
}
</style>
<script> 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; }
} //取消事件
function cancelEvent (event){
console.log("取消事件");
if(event.preventDefault){
event.preventDefault();
}else{
event.returnValue = false;
}
}
//取消传递
function cancelPropagation(event){
console.log("取消传递");
if(event.stopPropagation){
event.stopPropagation();
}else{
event.cancelBubble = true;
} }
function dragOver(evt){
console.log("拖拽进入区域");
if(evt.preventDefault)
evt.preventDefault();
evt = evt || window.event;
evt.dataTransfer.dropEffect = 'copy';
return false;
}
window.onload = function(){
console.log("程序就绪"); //console.log(target);
var item = document.getElementById("item"); item.setAttribute("draggable","true");
//console.log(item);
listenEvent(item,"dragstart",function(evt){
console.log("拖拽開始");
evt = evt || window.event;
evt.dataTransfer.effectAllowed = 'copy';
evt.dataTransfer.setData("Text",item.id); });
var target = document.getElementById("drop");
listenEvent(target,"dragenter",cancelEvent);
listenEvent(target,"dragover",dragOver);
listenEvent(target,"drop",function(evt){
console.log("drop");
cancelPropagation(evt);
evt = evt || window.event;
evt.dataTransfer.dropEffect = 'copy';
var id = evt.dataTransfer.getData("Text");
target.appendChild(document.getElementById(id));
}); }; </script>
</head> <body> <div>
<p>Drag the small yellow box with hte dash border to the larger red box with the solid border</p>
</div>
<div id = "item" draggable = "true">
</div>
<div id = "drop">
</div>
</body>
</html>