【问题标题】:Determine if element is behind another确定元素是否在另一个后面
【发布时间】:2018-09-19 22:35:27
【问题描述】:

有没有办法确定 elementA 是否在另一个元素“后面”,因此 elementA 对用户不可见?

显然可以使用stacking context,但问题是我们不知道应该查看哪些元素。因此,我们必须遍历 DOM 中的所有元素并为多个元素执行堆叠上下文比较。这在性能方面并不好。

这是一个 jsfiddle。那么有没有办法确定#hidden-element 对用户不可见,因为在它上面渲染了另一个元素?

https://jsfiddle.net/b9dek40b/5/

HTML:

<div id="covering-element"></div>
<div>
  <div id="hidden-element"></div>
</div>

样式:

#covering-element {
  position: absolute;
  width: 100px;
  height: 100px;
  background: darksalmon;
  text-align: center;
}

#hidden-element {
  width: 25px;
  height: 25px;
  background: deeppink;
}

【问题讨论】:

标签: javascript browser


【解决方案1】:

我们的解决方案是使用一些东西来确定元素是否可见,而不是在任何其他元素后面。这是我们使用的方法。

  1. window.getComputedStyle 检查visibility:hiddendisplay:none
  2. document.elementFromPoint 来自多个点。最常见的情况可能可以通过检查所有角落来处理。尽管我们需要更多积分才能获得更稳健的结果。使用Element.getBoundingClientRect() 可以轻松检查角坐标

https://jsfiddle.net/k591Lbwu/27/

HTML

<div id="covering-element"></div>
<div>
  <div id="hidden-element"></div>
</div>

<button style="margin-top:100px">Check visibility</button>

CSS

#covering-element {
  position: absolute;
  width: 100px;
  height: 100px;
  background: darksalmon;
  text-align: center;
}

#hidden-element {
  width: 25px;
  height: 25px;
  background: deeppink;
}

JavaScript

document.querySelector('button').addEventListener('click', function() {
    const element = document.getElementById('hidden-element')
  alert('Visible = '+isVisible(element))
})

function isVisible(element) {
  if(!isVisibleByStyles(element)) return false
  if(isBehindOtherElement(element)) return false
  return true
}

function isVisibleByStyles(element) {
    const styles = window.getComputedStyle(element)
  return styles.visibility !== 'hidden' && styles.display !== 'none'
}

function isBehindOtherElement(element) {
  const boundingRect = element.getBoundingClientRect()
  // adjust coordinates to get more accurate results
  const left = boundingRect.left + 1
  const right = boundingRect.right - 1
  const top = boundingRect.top + 1
  const bottom = boundingRect.bottom - 1

  if(document.elementFromPoint(left, top) !== element) return true
  if(document.elementFromPoint(right, top) !== element) return true
  if(document.elementFromPoint(left, bottom) !== element) return true
  if(document.elementFromPoint(right, bottom) !== element) return true

  return false
}

【讨论】:

    猜你喜欢
    • 2014-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-31
    • 2011-05-14
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多