js拖拽之三:碰撞切换颜色

时间:2024-04-06 11:17:37

原理图:
js拖拽之三:碰撞切换颜色
代码实现:
<style>
#div1{
width:50px;
height:50px;
background-color: black;
position:absolute;
top:0;
left:0;
}
#div2{
width:200px;
height:200px;
background-color: red;
position:absolute;
top:30%;
left:30%;
}
</style>
<body>
<div id="div2"></div>
<div id="div1"></div>
<script>
var oDiv = document.getElementById("div1");
var oDiv2 = document.getElementById("div2");
oDiv.onmousedown = function (ev){ //鼠标按下时:
ev = ev||event;
var disX = evclientX - oDiv.offsetLeft;
var disY = ev.clientY - oDiv.offsetTop;
document.onmousemove = function (ev){ //鼠标拖动时:
ev = ev||event;
oDiv1.style.left = ev.clientX - disX+'px';
oDiv1.style.top = ev.clientY - disY+'px';
var l1 = oDiv1.offsetLeft;
var r1 = oDiv1.offsetLeft + oDiv1.offsetWidth;
var t1 = oDiv1.offsetTop;
var b1 = oDiv1.offsetTop + oDiv.offsetHeight;
var l2 = oDiv2.offsetLeft;
var r2 = oDiv2.offsetLeft + oDiv2.offsetWidth;
var t2 = oDiv2.offsetTop;
var b2 = oDiv2.offsetTop + oDiv2.offsetHeight;
if(r1<l2 || l1>r2 || b1<t2 || t1>b2) { //左右上下四个方向 ,只要有任何一个成立就可发生碰撞
oDiv2.style.background = 'red';
}else
{
oDiv2.style.background = 'green';
}
}
document.onmouseup = function (){
document.onmousemove = document.onmouseup = null;
}
}
</script>
</body>
js拖拽之三:碰撞切换颜色
初始状态:
js拖拽之三:碰撞切换颜色
情况(1):左
js拖拽之三:碰撞切换颜色
情况(2):右
js拖拽之三:碰撞切换颜色
情况(3):上
js拖拽之三:碰撞切换颜色
情况(4):下
js拖拽之三:碰撞切换颜色
(前端小白,如有错误,欢迎指正~~)