There are situations where it can be useful to get the exact pixel width of an em
measurement. For example, suppose you have an element with a CSS property (like border or padding) which is measured in ems, and you need to get the exact pixel width of the border or padding. There's an existing question which touches on this topic:
How can i get default font size in pixels by using JavaScript or JQuery?
This question is asking about getting the default font size - which is necessary in order to convert a relative em
value to an exact px
value.
This answer has a pretty good explanation of how to go about getting the default font size of an element:
Since ems measure width you can always compute the exact pixel font
size by creating a div that is 1000 ems long and dividing its
client-Width property by 1000. I seem to recall ems are truncated to
the nearest thousandth, so you need 1000 ems to avoid an erroneous
truncation of the pixel result.
So, using this answer as a guide, I wrote the following function to get the default font size:
function getDefaultFontSize(parentElement)
{
parentElement = parentElement || document.body;
var div = document.createElement('div');
div.style.width = "1000em";
parentElement.appendChild(div);
var pixels = div.offsetWidth / 1000;
parentElement.removeChild(div);
return pixels;
}
Once you have the default font size, you can convert any em
width to px
width by just multiplying the ems by the element's default font size and rounding the result:
Math.round(ems * getDefaultFontSize(element.parentNode))
Problem: The getDefaultFontSize
is ideally supposed to be a simple, side-effect free function that returns the default font size. But it DOES have an unfortunate side effect: it modifies the DOM! It appends a child and then removes the child. Appending the child is necessary in order to get a valid offsetWidth
property. If you don't append the child div
to the DOM, the offsetWidth
property remains at 0 because the element is never rendered. Even though we immediately remove the child element, this function can still create unintended side effects, such as firing an event (like Internet Explorer's onpropertychange
or W3C's DOMSubtreeModified
event) that was listening on the parent element.
Question: Is there any way to write a truly side-effect free getDefaultFontSize()
function that won't accidentally fire event handlers or cause other unintended side effects?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…