让我为大家带来一个小案例吧!
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title></title><style>* {margin: 0;padding: 0;}.box1 {width: 100px;height: 100px;background-color: black;margin-bottom: 10px;position: relative;left: 0;top: 0;}.box2 {width: 100px;height: 100px;background-color: pink;margin-bottom: 10px;margin-left: 200px;}.box3 {width: 100px;height: 100px;background-color: orange;margin-top: 120px;margin-left: 200px;}</style></head><body><div class="box1"></div><div class="box2"></div><div class="box3"></div></body><script>//获取要移动的盒子var div = document.querySelector(".box1")//获取其他2个盒子var div1=document.querySelector(".box2")var div2=document.querySelector(".box3")div.onmousedown = function(e){//获取盒子距离页面多少var divX =div.offsetLeftvar divY =div.offsetTop//获取盒子点击的xy坐标var downX =e.clientXvar downY =e.clientYdocument.onmousemove=function(e){console.log(e);// if(div.offsetLeft<1){// alert("超出")// }//获取盒子点击的地方距离document点击的坐标的差var moveX =e.clientX - downXvar moveY =e.clientY - downY//获取移动鼠标想放哪放哪// div.style.left =divX+moveX+"px"// div.style.top =divY+moveY+"px"//这个的中心点在中间div.style.left =e.clientX - div.offsetWidth/2+"px"div.style.top =e.clientY - div.offsetHeight/2+"px"//拿他们的宽高去判断坐标if(e.clientX<div1.offsetWidth+div.offsetWidth/2+200&&e.clientX>div1.offsetWidth+div.offsetWidth/2&&e.clientY>div1.offsetTop/2&&e.clientY<div1.offsetTop*2+40){console.log(div1.offsetTop);div1.style.backgroundColor="green"}else{div1.style.backgroundColor="pink"}//拿他们的距离去判断if(e.clientX<div2.offsetWidth+div.offsetWidth/2+200&&e.clientX>div1.offsetWidth+div.offsetWidth/2&&e.clientY>div2.offsetTop-div.offsetHeight/2&&e.clientY<div2.offsetTop+div.offsetHeight+div.offsetHeight/2){div2.style.backgroundColor="blue"}else {div2.style.backgroundColor="orange"}}}//如果按起就不动div.onmouseup = function(){document.onmousemove = null}</script>
</html>
效果图:
感谢大家的阅读,如有不对的地方,可以向我提出,感谢大家!