javascript 要素同士が重なっているかを判定する

javascript 要素同士が重なっているかを判定する

javascriptで、要素同士が重なっているかを判定するサンプルコードを記述してます。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 105.0.5195.127

要素同士が重なっているかを判定

要素同士が重なっているかを判定するには「getBoundingClientRect」を使用してhtml要素の座標を取得して比較します。

<div id="box1" style="width: 100px; height: 100px; border: 1px dashed #333333; position:absolute;">
  Box1
</div>

<div id="box2" style="width: 80px; height: 150px; border: 1px dashed #333333;padding-top: 50px;">
  Box2
</div>

<div id="box3" style="width: 100px; height:100px; border: 1px dashed #333333; margin-top: 50px;">
  Box3
</div>

<script>

function check(elm1, elm2) {

  const d1 = elm1.getBoundingClientRect();
  const d2 = elm2.getBoundingClientRect();

  return !(
    d1.top > d2.bottom ||
    d1.right < d2.left ||
    d1.bottom < d2.top ||
    d1.left > d2.right
  );

}

const elm1 = document.getElementById('box1');
const elm2 = document.getElementById('box2');
const elm3 = document.getElementById('box3');

console.log(check(elm1, elm2)); // true

console.log(check(elm1, elm3)); // false

console.log(check(elm2, elm3)); // false

</script>

実行結果