peg*_*ggy 6 html javascript css
我正在用 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>
Run Code Online (Sandbox Code Playgroud)
实现此目的的一种方法是获取Element#getBoundingClientRect()被分类为重叠、包含等的 DOM 元素的绝对坐标。
此函数返回相应 DOM 元素的top、right和坐标bottom,您可以使用它们来确定 an相对于 a的包含。leftelementcontainer
您可以实现如下所示的函数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))Run Code Online (Sandbox Code Playgroud)
.main {
width: 50%;
height: 200px;
border: 5px solid #000;
position: relative;
}
.obj {
width: 40px;
height: 40px;
border: 1px solid blue;
position: absolute;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
这也是一个工作小提琴- 希望有帮助!