检查哪个元素高于其他

时间:2019-02-22 16:07:42

标签: javascript overlapping

说我有两个重叠的盒子(fiddle

<html>
<body>
    <div class="box">element 1</div>
    <div class="box" style="left: 20px; top: 10px; background-color: red;">element 2</div>
    <style>
      .box {
        background-color: green;
        position: absolute;
        width: 100px;
        height: 100px;
        border: 1px sold red;
      }
    </style>
</body>
</html>

在香草javascript中,有没有办法分辨哪个框位于另一个框上方?我只关心用户在视觉上的感受。

类似以下内容

isAbove(el1, el2) // false
isAbove(el2, el1) // true

2 个答案:

答案 0 :(得分:0)

我唯一想到的方法是获取所涉及元素的dom路径,并通过声明检查哪个先出现;在没有z-index的情况下,您应该会想到,哪个元素自然会显示在另一个元素的上方。

function getAncestors(ele) {
  var ancestors = [ele];
  while(ele.parentElement) { // walk all parents and get ancestor list
    ele = ele.parentElement;
    ancestors.push(ele);
  }
  return ancestors.reverse(); // flip list so it starts with root
}

function declaredBefore(ele1,ele2) {
  var a1 = getAncestors(ele1);
  var a2 = getAncestors(ele2);
  for(var i=0;i<a1.length;i++) { // check path, starting from root
     if(a1[i] !== a2[i]) { // at first divergent path
        var testNodes = a1[i-1].childNodes; // get children of common ancestor
        for(var j=0;j<testNodes.length;j++) { // check them for first disparate ancestor
            if(testNodes[j] === a1[i]) { return true; } // ele1 is first
            if(testNodes[j] === a2[i]) { return false; } // ele2 is first
        }
     }
  }
  return undefined; // could not determine who was first
}

function isAbove(ele1, ele2) {
  // rudimentary z-index check for eles sharing a parent 
  if(ele1.parentNode === ele2.parentNode) {
    var z1 = ele1.style.zIndex;
    var z2 = ele2.style.zIndex;
    if(z1 !== undefined && z2 !== undefined) { // if both have z-index, test that
      return z1 > z2;
    }
  }
  return declaredBefore(ele2, ele1); // if 2 is declared before 1, 1 is on top
}

此解决方案远非防弹,但至少应让您知道哪个元素最后声明,并考虑dom树的层次结构。除非元素共享父级,否则它也不会比较zIndex,尽管您也可以修改它以检查父级的zIndex层次结构。

答案 1 :(得分:0)

只需获取这些元素的zIndex并进行比较