I'm looking for a reliable way to get the width of the window in em units using javascript. I was surprised to see that jQuery will only return a result in pixel measurements. Any help is appreciated.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
- jQuery add and remove delay
It's possible to calculate it, but
em
isn't a "simple" unit likepx
because it depends on a font selection (that is, a combination of typeface family, style (bold, italic, etc), and font size). Of course font size itself can be relative (e.g. if you give a font anem
,ex
, or percentage size then the computedpx
height for that font is derived from the parent element's size).To get the
em
width of a page you could do the conversion like this (warning: psuedocode):For those who need it all put together, this code works for me:
It's put together using the answer above added to the window-width test code found in the linked tutorial.
This seems to work:
Here's a solution that doesn't require jQuery, and doesn't require an explicit font-size declaration.
Simple, since we know
1em = 16px