<!DOCTYPE html>
<html>
<head>
<title>js拖拽效果</title>
<style type="text/css">
.parent{
position: relative;
}
#drop{
300px;
height: 200px;
background-color: #ff0000;
padding: 5px;
border:2px solid #000000;
position: absolute;
left: 200px;
top: 0px;
overflow: hidden;
}
#item{
100px;
height: 100px;
background-color: #ffff00;
padding: 5px;
position: absolute;
left: 0;
top:0;
border:1px dashed #000000;
}
.copyitem0,.copyitem1,.copyitem2,.copyitem3{
100px;
height: 100px;
background-color: #ffff00;
padding: 5px;
left: 0;
top:0;
float: left;
border:1px dashed #000000;}
*[draggable=true]{
-webkit-user-select:none;/*禁止选择文字*/
-khtml-user-drag:element;/*兼容safai 设置元素可拖拽*/
cursor: move;
}
*:-khtml-drag{
background-color: rgba(238,238,238,0.5);
}
</style>
<script type="text/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 index=0;//标记拖拽元素个数
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';
/*dataTransfer对象用来传递拖拽的数据。
*dataTransfer对象有 getData()和setData()两个主要方法,
*操作dataTransfer中携带的数据
*/
var id=evt.dataTransfer.getData("Text");
var item=document.getElementById(id);
/*将拖拽div复制一份放入目标div中*/
var copyitem=document.createElement("div");
copyitem.className='copyitem'+index;
copyitem.innerHTML=item.innerHTML;
target.appendChild(copyitem);
index++;
});
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;
}
</script>
</head>
<body>
<div>
<p>把黄色小块拖入红色大方框中</p>
</div>
<div class="parent">
<!-- onselectstart="return false;"禁止选择文字兼容IE -->
<div id="item" draggable="true" onselectstart="return false;">hello</div>
<div id="drop"></div>
</div>
</body>
</html>