Skip to content

Instantly share code, notes, and snippets.

@manabuyasuda
Last active November 25, 2021 02:47
Show Gist options
  • Select an option

  • Save manabuyasuda/36d778f73b562515ea08c98b55003e5c to your computer and use it in GitHub Desktop.

Select an option

Save manabuyasuda/36d778f73b562515ea08c98b55003e5c to your computer and use it in GitHub Desktop.
/**
* 要素の高さを取得します。
* @param {HTMLElement} target 高さを取得する要素
* @return {number} 小数点以下を含めた要素の高さ
* @example
* getHeight(document.querySelector('.foo'))
*/
const getHeight = target => {
const el = target
const isInvisibleElement =
window.getComputedStyle(el).getPropertyValue('display') === 'none' ||
window.getComputedStyle(el).getPropertyValue('height') === '0px'
// style属性値があれば保存、なければ空文字を保存する
const styleAttrDisplay = el.style.display === '' ? '' : el.style.display
const styleAttrPosition = el.style.position === '' ? '' : el.style.position
const styleAttrVisibility = el.style.visibility === '' ? '' : el.style.visibility
const styleAttrHeight = el.style.height === '' ? '' : el.style.height
// 高さが取得できない要素は、不可視状態で取得する
if (isInvisibleElement) {
el.style.setProperty('display', 'block', 'important')
el.style.setProperty('position', 'relative', 'important')
el.style.setProperty('visibility', 'hidden', 'important')
el.style.setProperty('height', 'auto', 'important')
}
// 高さを取得する
const elementHeight = el.getBoundingClientRect().height
// 元のstyle属性に戻す
if (isInvisibleElement) {
el.style.display = styleAttrDisplay
el.style.position = styleAttrPosition
el.style.visibility = styleAttrVisibility
el.style.height = styleAttrHeight
}
return elementHeight
}
export { getHeight }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment