如何检查两个圆形div是否重叠

3
这是我的codepen。我想用jQuery检查div是否重叠。我写了一段代码,但它只适用于正方形和矩形,并不适用于圆形div。我该如何使它适用于圆形div?

const coordinates = (className) => {
  const val = document.querySelector(className);
  
  return {
      y: val.offsetTop,
      x: val.offsetLeft,
      yh: val.offsetTop + val.offsetHeight,
      xw: val.offsetLeft + val.offsetWidth,
  }
}

const cm = coordinates(".circle.small");
const cl = coordinates(".circle.large");

const offset_x = cm.x < cl.x && cm.xw > cl.x;
const offset_xw = cm.x < cl.xw && cm.xw > cl.xw;
const offset_cx = cm.x < cl.xw && cm.xw < cl.xw;
const offset_cy = cm.y < cl.yh && cm.yh < cl.yh;
const offset_y = cm.y < cl.y && cm.yh > cl.y;
const offset_yh = cm.y < cl.yh && cm.yh > cl.yh;

const is_x = offset_x || offset_xw || offset_cx;
const is_y = offset_y || offset_yh || offset_cy;

console.log(is_x, is_y);
.circle {
  width: var(--square);
  height: var(--square);
  background: var(--bg);
  border-radius: 50%;
}

.parent {
  margin-left: 5px;
}

.parent2 {
  margin-left: 15px;
}

.small {
  --square: 50px;
  --bg: red;
  margin-bottom: -5px;
}

.large {
  --square: 100px;
  --bg: green;
}
<div class="parent">
  <div class="circle small"></div>
</div>
<div class="parent2">
  <div class="circle large"></div>
</div>

1个回答

2
你计算圆位置之间的差值的逻辑不太正确。你需要从每个圆的中心获取X和Y,然后计算从这两个点计算出来的斜边是否小于组合半径的一半。
下面是一个可行的例子。请注意,我只添加了jQuery / jQueryUI以使拖动圆更轻松进行测试 - 这些库在生产中并不需要使用。

let $label = $('.overlap-label span');

const hasOverlap = (x0, y0, r0, x1, y1, r1) => Math.hypot(x0 - x1, y0 - y1) <= r0 + r1;
const coordinates = (className) => {
  const el = document.querySelector(className);
  const rect = el.getBoundingClientRect();
  const radius = el.offsetHeight / 2;
  return {
    y: rect.top + radius,
    x: rect.left + radius,
    r: radius
  }
}
const checkForOverlap = () => {
  const cm = coordinates(".circle.small");
  const cl = coordinates(".circle.large");
  $label.text(hasOverlap(cm.x, cm.y, cm.r, cl.x, cl.y, cl.r));
}

$('.parent').draggable().on('drag', checkForOverlap);
.circle {
  width: var(--square);
  height: var(--square);
  background: var(--bg);
  border-radius: 50%;
  display: inline-block;
}

.parent {
  display: inline-block;
}

.small {
  --square: 50px;
  --bg: red;
}

.large {
  --square: 100px;
  --bg: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/themes/base/jquery-ui.min.css" />

<div class="overlap-label">Circles are overlapping? <span>false</span></div>
<div class="parent">
  <div class="circle small"></div>
</div>
<div class="parent">
  <div class="circle large"></div>
</div>


没问题,很高兴能帮忙 - 注意我刚刚编辑了答案以使其更加清晰。 - Rory McCrossan
如果其中一个 div 是正方形怎么办?我该如何处理? - Ghayas Ud Din

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接