我正在JavaScript做一个小游戏。我创建了一个小示例js小提琴演示链接。下面列出了三种情况:
根据让对象检测是否完全在其他对象JavaScript中,我知道如何检测目标内部的对象(情景C)。情况A和B怎么样?
<div class="main">
<div class="target"></div>
<div class="obj">A</div>
<div style="top:15%; left:50%;" class="obj">B</div>
<div style="top:25%; left:35%;" class="obj">C</div>
</div>发布于 2019-12-27 09:20:44
这样做的一种方法是使用Element#getBoundingClientRect()获取被分类为重叠、包含等的DOM元素的绝对坐标。
此函数返回到相应DOM元素的top、right、bottom和left coordiates,您可以使用这些元素来确定相对于container的element的包含。
您可以实现像下面所示的findContainment()这样的函数,其中element的包含是根据container元素分类的:
function findContainment(element, container) {
/*
Obtain the bounding rectangle for each element
*/
const brE = element.getBoundingClientRect()
const brC = container.getBoundingClientRect()
/*
If the boundaries of container pass through the boundaries of
element then classifiy this as an overlap
*/
if (
/* Does container left or right edge pass through element? */
(brE.left < brC.left && brE.right > brC.left) ||
(brE.left < brC.right && brE.right > brC.right) ||
/* Does container top or bottom edge pass through element? */
(brE.top < brC.top && brE.bottom > brC.top) ||
(brE.top < brC.bottom && brE.bottom > brC.bottom)) {
return "overlap";
}
/*
If boundaries of element fully contained inside bounday of
container, classify this as containment of element in container
*/
if (
brE.left >= brC.left &&
brE.top >= brC.top &&
brE.bottom <= brC.bottom &&
brE.right <= brC.right
) {
return "contained"
}
/*
Otherwise, the element is fully outside the container
*/
return "outside"
}
const main = document.querySelector(".main")
console.log("A", findContainment(document.querySelector(".a"), main))
console.log("B", findContainment(document.querySelector(".b"), main))
console.log("C", findContainment(document.querySelector(".c"), main))
console.log("D", findContainment(document.querySelector(".d"), main))
console.log("E", findContainment(document.querySelector(".e"), main)).main {
width: 50%;
height: 200px;
border: 5px solid #000;
position: relative;
}
.obj {
width: 40px;
height: 40px;
border: 1px solid blue;
position: absolute;
}<div class="main">
<div style="top:105%; left:25%;" class="obj a">A</div>
<div style="top:15%; left:-5%;" class="obj b">B</div>
<div style="top:20%; left:40%;" class="obj c">C</div>
<div style="top:20%; left:110%;" class="obj d">D</div>
<div style="top:90%; left:95%;" class="obj e">E</div>
</div>
这里有一个工作小提琴 -希望这有帮助!
https://stackoverflow.com/questions/59498298
复制相似问题