js碰撞检测
程序员文章站
2022-03-13 13:53:16
...
<!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>
div {
width: 150px;
height: 150px;
position: absolute;
left: 0px;
top: 0px;
background-color: red;
}
div:last-of-type{
background-color: yellowgreen;
left:300px;
top:300px;
}
</style>
</head>
<body>
<!-- <img src="./imgs/f1.jpg" alt=""> -->
<div></div>
<div></div>
<script>
var img = document.getElementsByTagName('img')[0];
var div = document.getElementsByTagName('div');
// 浏览器可视区域宽高
var clientW = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var clientH = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
// div的宽高
var divW = div[0].offsetWidth;
var divH = div[0].offsetHeight;
// 范围
var areaX = clientW - divW;
var areaY = clientH - divH;
div[0].onmousedown = function (e) {
// 鼠标按下的时候,求出鼠标的位置到div左边以及上边的距离
var ev = e ||window.event;
var x = ev.clientX - div[0].offsetLeft;
var y = ev.clientY - div[0].offsetTop;
document.onmousemove = function (e) {
var ev = e||window.event;
var moveX = ev.clientX - x;
var moveY = ev.clientY - y;
// 边界判断
if(moveX <=0){
moveX = 0;
}else if(moveX>=areaX){
moveX = areaX;
}
if(moveY <=0){
moveY = 0;
}else if(moveY>=areaY){
moveY = areaY;
}
div[0].style.left = moveX +'px';
div[0].style.top = moveY + 'px';
var leftA = div[0].offsetLeft;
var topA = div[0].offsetTop;
var rightA = div[0].offsetLeft+div[0].offsetWidth;
var bottomA = div[0].offsetTop+div[0].offsetHeight;
var leftB = div[1].offsetLeft;
var topB = div[1].offsetTop;
var rightB = div[1].offsetLeft+div[1].offsetWidth;
var bottomB = div[1].offsetTop+div[1].offsetHeight;
// 碰撞检测
if(!(rightA < leftB || bottomA < topB || leftA > rightB || topA > bottomB )){
div[1].style.backgroundColor = 'blue'
}else{
div[1].style.backgroundColor = ''
}
}
document.onmouseup = function(){
document.onmousemove = null;
}
}
</script>
</body>
</html>