拖拽碰撞
当拖动图片时,碰到页面中的天蓝色盒子,盒子会由天蓝色变成黄色。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
padding: 0px;
margin: 0px;
}
img {
width: 100px;
height: 100px;
position: absolute;
top: 0px;
left: 0px;
z-index: 3;
}
#box {
width: 200px;
height: 200px;
background-color: skyblue;
position: fixed;
top: 50%;
left: 50%;
margin-left: -100px;
margin-top: -100px;
}
</style>
</head>
<body>
<img src="./image/p4.jpg" alt="" id="image">
<div id="box"></div>
<script>
var box = document.getElementById("box");
var image = document.getElementById("image");
drag(box);
drag(image);
function drag(obj) {
document.onmousedown = function (ev) {
// return false;
var ev = window.even || ev;
// ev.clientX:从鼠标到body的距离,box.offsetLeft:conbox的边框到body的距离
var x = ev.clientX - obj.offsetLeft;//box到鼠标点击位置的水平距离
var y = ev.clientY - obj.offsetTop;
document.onmousemove = function (ev) {
var ev = window.even || ev;
var le = ev.clientX - x; //box水平边到body的距离
var to = ev.clientY - y;
// 固定盒子
var boxleft = box.offsetLeft;
var boxtop = box.offsetTop;
var boxright = box.offsetLeft + box.offsetWidth;
var boxbottom = box.offsetHeight + box.offsetTop;
// var boxright =
// 移动的图片
var moveright = image.offsetLeft + image.offsetWidth;
console.log(moveright, 111)
var moveleft = image.offsetLeft;
var movetop = image.offsetTop;
var movebottom = image.offsetTop + image.offsetHeight;
if (moveright < boxleft || moveleft > boxright || movetop > boxbottom || movebottom < boxtop) {
box.style.background = "skyblue";
} else {
box.style.background = "yellow";
}
if (le < 0) {
le = 0;
}
if (le > document.documentElement.clientWidth - obj.offsetWidth) {
le = document.documentElement.clientWidth - obj.offsetWidth;
}
if (to < 0) {
to = 0;
}
if (to > document.documentElement.clientHeight - obj.offsetHeight) {
le = document.documentElement.clientHeight - obj.offsetHeight;
}
obj.style.left = le + "px";
obj.style.top = to + "px";
}
document.onmouseup = function () {
document.onmousemove = null;
}
return false;
}
}
</script>
</body>
</html>
结果:(上下左右碰撞颜色都会变)