拖拽图形碰撞变色效果
效果如下

拖拽后

代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>拖拽</title>
<style>
#div1 {
width: 100px;
height: 100px;
background: lightblue;
position: absolute;
left: 0;
top: 0px;
}
#div2 {
width: 100px;
height: 100px;
background: lightgreen;
position: absolute;
left: 500px;
top: 100px;
}
</style>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
</body>
</html>
<script>
var div1 = document.getElementById('div1')
var div2 = document.getElementById('div2')
//获取本次事件
div1.onmousedown = function (event) {
console.log(event.clientX)
console.log(div1.offsetLeft)//获取div1的left值
var chaX = event.clientX - div1.offsetLeft
var chaY = event.clientY - div1.offsetTop
document.onmousemove = function (event) {
if (
// ((div1r+div2r)*(div1r+div2r)>=(div2.offsetLeft-div1.offsetLeft)*(div2.offsetLeft-div1.offsetLeft)+(div2.offsetTop-div1.offsetTop)*(div2.offsetTop-div1.offsetTop))
(div1.offsetLeft + div1.offsetWidth >= div2.offsetLeft && div1.offsetLeft <= div2.offsetLeft + div2.offsetWidth)
&& (div1.offsetTop + div1.offsetHeight > div2.offsetTop && div1.offsetTop <= div2.offsetTop + div2.offsetHeight)
) {
div2.style.background = 'lightpink'
} else {
div2.style.background = 'lightgreen'
}
console.log(event.clientX)
div1.style.left = event.clientX - chaX + 'px'
div1.style.top = event.clientY - chaY + 'px'
}
}
</script>
首先定义两个盒子
然后在JS中获取两个盒子的DOM
代码如下
var div1 = document.getElementById('div1')
var div2 = document.getElementById('div2')
所谓拖拽,就是调用鼠标事件
首先鼠标按下
然后
鼠标移动
代码如下
div1.onmousedown = function (event) {
console.log(event.clientX)
console.log(div1.offsetLeft)//获取div1的left值
var chaX = event.clientX - div1.offsetLeft
var chaY = event.clientY - div1.offsetTop
}
首先鼠标按下获取本次事件
然后定义本次x轴的差值,为当前鼠标和div1的当前的left值
和定义本次y轴的差值,为当前鼠标和div1的当前的top值
鼠标按下就获取他
然后我们进行鼠标移动实现的效果
代码如下
document.onmousemove = function (event) {
if (
(div1.offsetLeft + div1.offsetWidth >= div2.offsetLeft && div1.offsetLeft <= div2.offsetLeft + div2.offsetWidth)
&& (div1.offsetTop + div1.offsetHeight > div2.offsetTop && div1.offsetTop <= div2.offsetTop + div2.offsetHeight)
) {
div2.style.background = 'lightpink'
} else {
div2.style.background = 'lightgreen'
}
console.log(event.clientX)
div1.style.left = event.clientX - chaX + 'px'
div1.style.top = event.clientY - chaY + 'px'
}
首先我们当鼠标滑动的时候触发本次函数
然后我们做判断
如果要实现碰撞变色的效果
我们思考
当div1的当前的left值加上当前的宽度>=div2的当前的left值
并且
div1的当前的left值<=div2的当前的left值+div2当前的宽度
并且
当div1的当前的top值加上当前的高度>=div2的当前的top值
并且
div1的当前的top值<=div2的当前的top值+div2当前的高度
JS代码如下
(div1.offsetLeft + div1.offsetWidth >= div2.offsetLeft && div1.offsetLeft <= div2.offsetLeft + div2.offsetWidth)
&& (div1.offsetTop + div1.offsetHeight > div2.offsetTop && div1.offsetTop <= div2.offsetTop + div2.offsetHeight)
设置它变色
然后我们设置它移动效果
div1.style.left = event.clientX - chaX + 'px'
div1.style.top = event.clientY - chaY + 'px'
就可以实现他的效果了

浙公网安备 33010602011771号