拖拽div靠近另一个div,改变另一个div颜色
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<style type="text/css">
.h1 {
width: 100px;
height: 100px;
background: red;
position: absolute;
z-index: 999;
}
.h2{
width: 100px;
height: 100px;
background: red;
top: 200px;
left: 200px;
position: absolute;
}
body{
margin: 0;
padding: 0;
}
</style>
<body>
<div class="h1">
</div>
<div class="h2"></div>
</body>
<script type="text/javascript">
var h1 = document.getElementsByClassName("h1")[0]
var h2 = document.getElementsByClassName("h2")[0]
h1.onmousedown = function(e) {
var x = e.clientX - h1.offsetLeft
var y = e.clientY - h1.offsetTop
document.onmousemove = function(e) {
h1.style.left = e.clientX - x + "px";
h1.style.top = e.clientY - y + "px";
if(h1.offsetLeft+h1.offsetWidth >= h2.offsetLeft && h1.offsetTop + h1.offsetHeight >= h2.offsetTop && h1.offsetLeft<=h2.offsetWidth + h2.offsetLeft && h1.offsetTop <= h2.offsetHeight + h2.offsetTop) {
h2.style.background= colorwehe()
}else{
h2.style.background='red'
}
}
}
document.onmouseup = function() {
document.onmousemove = null;
}
function colorwehe() {
var a = Math.floor(Math.random() *256);
b = Math.floor(Math.random() * 256);
c = Math.floor(Math.random() * 256)
return "rgb(" + a + "," + b + "," + c +")"
}
</script>
</html>
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/293cf89c251060905abc7ab9dc96b112.png#pic_center)