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

标签 javascript jquery

我正在创建一个灯箱 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/

相关文章:

javascript - 属性(property)范围问题?

javascript - 在 HTML 中使用三元运算符来决定要实现的类

javascript - 为什么从未达到该功能?

javascript - Angular 2 : Open ngbPopover containing image delayed on hover

javascript - 使用带有 jquery 的内部数组第一项从数组中删除数组

javascript - 有没有办法在javascript中的指定位置识别页面上的元素?

javascript - 添加脚本代码的链接

javascript - 获取评论之间的内容

javascript - 是否可以渲染具有隔离范围的 Angular Directive(指令)模板?

javascript在Safari中下载csv数据