js拖拽陰影
阿新 • • 發佈:2018-06-19
absolute get turn IV create ech 再次 pen eth
css如下
#box{ width: 200px; height: 200px; position: absolute;background-color: red;} .border_box{ position: absolute; width: 200px; height: 200px; opacity: 0.5; background-color: red;}
html如下
<div id="box"></div>
javascript如下
var oBox=document.getElementById(‘box‘); oBox.onmousedown=function(ev){ var oEvent=ev || event; var disX=oEvent.clientX-oBox.offsetLeft; var disY=oEvent.clientY-oBox.offsetTop; //鼠標位置減去box位置 var left=0; var top=0; var oBorderBox=document.createElement(‘div‘); oBorderBox.className="border_box"; oBorderBox.style.left=oBox.offsetLeft+‘px‘;; oBorderBox.style.top=oBox.offsetTop+‘px‘; document.body.appendChild(oBorderBox); document.onmousemove=function(ev){ //oBox改成document是怕速度拖拽速度快,鼠標偏離了box var oEvent=ev || event; left = oEvent.clientX - disX; top= oEvent.clientY - disY; oBorderBox.style.left=left+‘px‘; oBorderBox.style.top=top+‘px‘; } document.onmouseup=function(){ //oBox改成document是防止鼠標拖拽出可視區發生不了oBox.onmouseup事件 if( !collision( oBorderBox,oBox ) ){ oBox.style.left = left + "px"; oBox.style.top = top + "px"; } document.onmousemove=null; document.onmouseup=null; document.body.removeChild(oBorderBox); } return false; //解決FF再次拖拽出現兩個oBox的bug } /* obj1:拖拽的元素 obj2:被碰撞的元素 */ function collision(obj1,obj2){ var obj1L = obj1.offsetLeft; var obj1LW = obj1L + obj1.offsetWidth; var obj1T = obj1.offsetTop; var obj1TH = obj1T + obj1.offsetHeight; var obj2L = obj2.offsetLeft; var obj2LW = obj2L + obj2.offsetWidth; var obj2T = obj2.offsetTop; var obj2TH = obj2T + obj2.offsetHeight; if( obj1LW < obj2L || obj1L > obj2LW || obj1TH < obj2T || obj1T > obj2TH){ return false; } return true; }
js拖拽陰影