LoginSignup
6
6

More than 5 years have passed since last update.

要素が表示されているかどうかをチェック

Posted at

該当する要素だけでなく、親要素も表示されているかどうかをチェックしたい。
まだchromeでしか試してないが、このような結果になった。

  • 親要素が visibility: hidden だと子要素も visibility: hidden になる
  • 親要素が display: none だと、子要素の computedStyle.width、computedStyle.height が auto になる。または element.offsetParent が null になる
  • 親要素の height,width が 0px で、overflow: hidden の場合は、子要素で判定できないので、再帰的親要素をさかのぼってチェックする
export default function VisibilityCheck(targetElement: HTMLElement): boolean {
  if (targetElement.offsetParent === null) {
    return false
  }

  let target: HTMLElement | null = targetElement
  do {
    const style = getComputedStyle(target)

    if (style.display === 'none'
      || style.visibility !== 'visible'
      || parseFloat(style.opacity || '') <= 0.0
      || parseInt(style.height || '', 10) <= 0
      || parseInt(style.width || '', 10) <= 0
    ) {
      return false
    }

    target = target.parentElement
  } while (target !== null)

  return true
}
6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6