-
-
Save JodiWarren/19a24af76bd62eee06a282fb329771ba to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const containerStyle = { | |
display: "inline-block", | |
position: "absolute", | |
visibility: "hidden", | |
zIndex: -1, | |
}; | |
interface IEnhanceMeasurableNodeCallback { | |
(e: Node): Node; | |
} | |
export const measureDomNode = ( | |
node: HTMLElement, | |
enhanceMeasurableNode: IEnhanceMeasurableNodeCallback = (e) => e | |
) => { | |
const container = document.createElement("div"); | |
Object.entries(containerStyle).forEach(([prop, value]) => { | |
// @ts-ignore | |
container.style[prop] = value; | |
}); | |
const clonedNode = node.cloneNode(true); | |
const content = enhanceMeasurableNode(clonedNode); | |
container.appendChild(content); | |
if (node.parentNode) { | |
node.parentNode.appendChild(container); | |
} else { | |
document.body.appendChild(container); | |
} | |
const height = container.clientHeight; | |
const width = container.clientWidth; | |
container.parentNode?.removeChild(container); | |
return { height, width }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment