*{padding: 0;margin: 0}
ul,li{list-style: none} /* ul{width: 120px;height: 120px;margin: 100px auto;border: 1px solid #333;} */ li{width: 50px;height: 50px;background:#ddd;float: left;margin-left: 10px;margin-top:50px;position: absolute;left: 0;top: 0;} li:nth-of-type(2){left:60px;top: 0} li:nth-of-type(3){left:0;top: 60px} li:nth-of-type(4){left:60px;top: 60px} js:
window.onload=function(){ var oUl=document.querySelector('ul'); var oLi=document.querySelectorAll('li'); for(var i=0;i<oLi.length;i++){ drag(oLi[i]) }; function drag(obj){ obj.onmousedown=function(ev){ var ev =ev||window.event; var disX =ev.clientX -obj.offsetLeft+parseInt(getStyle(obj,'marginLeft')); var disY =ev.clientY -obj.offsetTop+parseInt(getStyle(obj,'marginTop')); console.log(parseInt(getStyle(obj,'marginLeft'))); document.onmousemove=function(ev){ var ev =ev||window.event; obj.style.left =ev.clientX -disX+'px'; obj.style.top =ev.clientY -disY+'px'; for(var i=0;i<oLi.length;i++){ touch(obj,oLi[i]); };
}; document.onmouseup=function(){ document.onmouseDown =null; document.onmousemove=null }; return false; }; }; function touch(obj1,obj2){ var l1=obj1.offsetLeft; var r1=obj1.offsetLeft+obj1.offsetWidth; var t1=obj1.offsetTop; var b1=obj1.offsetTop+obj1.offsetHeight;
var l2=obj2.offsetLeft; var r2=obj2.offsetLeft+obj2.offsetWidth; var t2=obj2.offsetTop; var b2=obj2.offsetTop+obj2.offsetHeight; if(b1<t2 || l1>r2 || t1>b2 || r1<l2 ){ console.log("碰不到") }else{ console.log("碰到了") obj2.style.background='red' } }; function getStyle(obj,name){ if (obj.currentStyle) { return obj.currentStyle[name]; }else{ return getComputedStyle(obj,false)[name]; } } }html:
<ul> <li></li> <li></li> <li></li> <li></li> </ul>