js拖拽阴影
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; }
posted on 2018-06-19 10:56 婆婆买了只kitty 阅读(251) 评论(0) 编辑 收藏 举报