Last active
December 14, 2015 04:19
-
-
Save DigiTec/5027055 to your computer and use it in GitHub Desktop.
This Gist uses a cached, hidden div in order to measure height/width of text. Imperfect since I'm still technically inheriting styles through the body that could affect my offsetWidth and offsetHeight but most likely a better approximation than measuring the width of the "M" character which is often a suggestion when dealing with the lack of hei…
This file contains hidden or 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
(function () { | |
var _cachedDiv; | |
function domMeasureText(text, font) { | |
if (!_cachedDiv) { | |
_cachedDiv = document.createElement("div"); | |
_cachedDiv.style.visibility = "hidden"; | |
_cachedDiv.style.position = "absolute"; | |
document.body.appendChild(_cachedDiv); | |
} | |
_cachedDiv.style.font = font; | |
_cachedDiv.innerText = text; | |
return { width: _cachedDiv.offsetWidth, height: _cachedDiv.offsetHeight }; | |
} | |
this.domMeasureText = domMeasureText; | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment