gpt4 book ai didi

javascript - 检测元素是否超出其父元素的外边界

转载 作者:行者123 更新时间:2023-12-03 03:50:18 24 4
gpt4 key购买 nike

我正在创建一个灯箱 jQuery 插件,灯箱(图像)内部有绝对定位的元素(图像内部)。

enter image description here

这些元素将随机添加到红色图像的顶部。目前,这些蓝色方 block 将与红色图像的外边界重叠。

我怎样才能检测到这种行为?蓝色有时会被隐藏,然后,在单击时,它会扩展到红色的外部边界。

最佳答案

您可以找到每个元素的边界框,并对边缘进行快速比较,以检测它是在元素内部还是外部。

var isItIn = function(parent, child) {
var box1coords = parent.getBoundingClientRect();
var box2coords = child.getBoundingClientRect();

if (
box2coords.top < box1coords.top ||
box2coords.right > box1coords.right ||
box2coords.bottom > box1coords.bottom ||
box2coords.left < box1coords.left) {

return true;
}

return false;

}

console.log(isItIn(document.querySelector('.box1'), document.querySelector('.box2')));

console.log(isItIn(document.querySelector('.box1'), document.querySelector('.box3')));
.box1 {
width: 400px;
height: 400px;
background-color: red;
position: absolute;
top: 100px;
left: 100px;
}

.box2 {
width: 100px;
height: 100px;
background-color: blue;
position: absolute;
top: 50px;
left: 300px;

}

.box3 {
width: 50px;
height: 50px;
background-color: green;
position: absolute;
top: 200px;
left: 150px;

}
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>

关于javascript - 检测元素是否超出其父元素的外边界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45199518/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com