首页 > 代码库 > 拖拽函数封装,元素碰撞

拖拽函数封装,元素碰撞

function drag(obj){

obj.onmousedown = function(ev){
var ev = ev || event;
//鼠标点击位置到图片两侧距离
var ol = ev.clientX - this.offsetLeft;
var ot = ev.clientY - this.offsetTop;

//非标准ie下利用全局捕获占用接下来的事件,相当于阻止浏览器默认行为
if(obj.setCapture){
obj.setCapture();
}

document.onmousemove = function(ev){
var ev = ev || event;
//移动时方块位置
var oL = ev.clientX - ol;
var oT = ev.clientY - ot;

obj.style.left = oL + ‘px‘;
obj.style.top = oT + ‘px‘;

//碰撞 九宫格排除法
var L1 = obj.offsetLeft;
var T1 = obj.offsetTop;
var R1 = obj.offsetLeft + obj.offsetWidth;
var B1 = obj.offsetTop + obj.offsetHeight;
var L2 = oDiv.offsetLeft;
var T2 = oDiv.offsetTop;
var R2 = oDiv.offsetLeft + obj.offsetWidth;
var B2 = oDiv.offsetTop + obj.offsetHeight;

if( R1<L2 || L1>R2 || B1<T2 || T1>B2 ){
oDiv.style.background = ‘‘;
}else{
oDiv.style.backgroundColor = ‘red‘;
}


}

document.onmouseup = function(){
document.onmouseup = document.onmousemove = null;
//鼠标抬起后解除全局捕获
if(obj.releaseCapture){
obj.releaseCapture();
}
}

//标准浏览器阻止文字、图片拖动默认行为
return false;
}
}

拖拽函数封装,元素碰撞