仿h5拖拽
在h5中有个拖拽的声明式命令,就如html属性一样,简单强大。
而在网页上拖拽的功能还是需求很大的,所以对这方面应该去仔细了解一下。
所以仿一一下它的实现。只是仿了它的复制一份到目标容器的功能。它还有很多功能。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <style> .dragBox{ position: absolute; top: 100px; left: 100px; width: 100px; height: 100px; border-radius: 50%; background: red; } .dragBox:after{ content: ""; display: block; position: absolute; width: 40px; height: 40px; border: 1px solid #eee; left: -20px; top: 0px; border-left:1px solid #ff7600; border-top: 1px solid #ff4500; transform: rotate(-10deg); } .dragBox:before{ content: ""; display: block; position: absolute; width: 40px; height: 40px; border: 1px solid #eee; right: 0px; top: -20px; border-left:1px solid #ff7600; border-top: 1px solid #ff4500; transform: rotate(90deg); } .target{ position: absolute; top: 200px; left: 50px; width: 100%; height: 100px; } .opacity{ opacity: .5; } .border{ border: 1px dashed #000; } .target01{ position: absolute; top: 10px; left: 0; width: 80%; height: 50px; } </style> <div class="dragBox target0"> </div> <div class="target"> <div class="target01"></div> </div> <script> /*容器位置*/ var posData=[{top:pos($(".target")).top,left:pos($(".target")).left,obj:$(".target"),placePosJudge:false}, {top:pos($(".target01")).top,left:pos($(".target01")).left,obj:$(".target01"),placePosJudge:false}]; function $(objStr){ return document.querySelector(objStr); } /*获取单个容器位置,相对于window的位置*/ function pos(obj,offset){ if(!offset){ offset={top:0,left:0}; } offset.top+=obj.offsetTop; offset.left+=obj.offsetLeft; if(!obj.offsetParent){ return offset; } return pos(obj.offsetParent,offset); } (function(undefined){ var oDargBox=$(".dragBox"); var oDiv=$(".target"); document.onmousedown=function(e){ e=e||window.event; if(e.target.className.indexOf("target0")!=-1){ var obj=e.target, objClone=obj.cloneNode(true), posX=e.clientX-obj.offsetLeft, posY=e.clientY-obj.offsetTop, index=-1; objClone.classList.add("opacity"); document.body.appendChild(objClone); document.onmousemove=function(e){ e=e||window.event; var X=e.clientX-posX,Y=e.clientY-posY; objClone.style.left=X+"px"; objClone.style.top=Y+"px"; /*使用碰撞检测来检测容器范围*/ for(var i=0;i<posData.length;i++){ if(posData[i].top<Y+100&& Y<posData[i].top+300&& posData[i].left<X+100&& X<posData[i].left+300){ for(var j=0;j<posData.length;j++){ posData[j].placePosJudge=false; } posData[i].placePosJudge=true; posData[i].obj.classList.add("border"); }else{ posData[i].obj.classList.remove("border"); } } } document.onmouseup=function(){ objClone.classList.remove("opacity"); document.onmousemove=document.onmouseup=null; for(var i=0;i<posData.length;i++){ posData[i].obj.classList.remove("border"); if(posData[i].placePosJudge){ posData[i].obj.appendChild(objClone); objClone.style.position="relative"; objClone.style.top="0"; objClone.style.left="0"; return false; } } document.body.removeChild(objClone); return false; } } } })() </script> </body> </html>