第一种
/**
* 判断两个区域是否相交
* 判断A的left或right 是否在B的left-right区间内
* &&
* 判断A的top或bottom 是否在B的top-bottom区间内
* */
const isRectOverlap = (rectA?: DOMRect, rectB?: DOMRect): boolean => {
if (!rectA || !rectB) return false;
const { left: leftA, right: rightA, bottom: bottomA, top: topA } = rectA;
const { left: leftB, right: rightB, bottom: bottomB, top: topB } = rectB;
const isInRowArea = (pointX: number) => leftB <= pointX && pointX <= rightB;
const isInColArea = (pointY: number) => topB <= pointY && pointY <= bottomB;
const isOverlapRow = isInRowArea(leftA) || isInRowArea(rightA);
const isOverlapCol = isInColArea(topA) || isInColArea(bottomA);
return isOverlapRow && isOverlapCol;
};
第二种
const isRectOverlap = (rect1?: DOMRect, rect2?: DOMRect): boolean => {
if (!rect1 || !rect2) {
return false;
}
const [l1, t1, r1, b1] = [
rect1.x,
rect1.y,
rect1.x + rect1.width,
rect1.y + rect1.height,
];
const [l2, t2, r2, b2] = [
rect2.x,
rect2.y,
rect2.x + rect2.width,
rect2.y + rect2.height,
];
return !(l1 > r2 || r1 < l2 || t1 > b2 || b1 < t2);
};
使用:
const targetNode = hotArea.getBoundingClientRect();
const currentNode = optionArea.getBoundingClientRect();
const isInHotArea = isRectOverlap(targetNode, currentNode);