Is it possible to get the width of the window in em units using javascript?

强颜欢笑 提交于 2019-12-03 04:43:54

问题


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.


回答1:


This seems to work:

$(window).width() / parseFloat($("body").css("font-size"));



回答2:


Here's a solution that doesn't require jQuery, and doesn't require an explicit font-size declaration.

window.innerWidth / parseFloat(
  getComputedStyle(
    document.querySelector('body')
  )['font-size']
)



回答3:


For those who need it all put together, this code works for me:

<p>Window size: <span id="width_px"></span> pixels or <span id="width_ems"></span> ems</p>
<script>
  window.onresize = function() {
    document.getElementById("width_px").innerHTML = window.innerWidth;
    document.getElementById("width_ems").innerHTML = window.innerWidth / parseFloat($("body").css("font-size"));
  };
</script>

It's put together using the answer above added to the window-width test code found in the linked tutorial.




回答4:


It's possible to calculate it, but em isn't a "simple" unit like px 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 an em, ex, or percentage size then the computed px 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 this to work reliably, size should be in px, pt, or mm.
function getWindowWidthInEm(fontFamily, style, size) {
    var box = document.createElement("span");
    box.innerText = "M";
    box.style.fontFamily = fontFamily;
    box.style.fontSize   = size;
    box.style.fontWeight = style is bold;
    box.style.fontStyle  = style is italic;

    var body = document.getElementsByTagName("body")[0];
    body.appendChild( box );

    var emInPx = box.getComputedStyle().width;

    body.removeChild( box );

    var windowPx = window.width;
    return windowx / emInPx;
}



回答5:


Simple, since we know 1em = 16px

var window_width_em = 1/16 * window_width_px;


来源:https://stackoverflow.com/questions/12241251/is-it-possible-to-get-the-width-of-the-window-in-em-units-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!