Is it possible to get the width of the window in e

2020-05-16 19:33发布

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.

5条回答
够拽才男人
2楼-- · 2020-05-16 20:06

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;
}
查看更多
欢心
3楼-- · 2020-05-16 20:13

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楼-- · 2020-05-16 20:14

This seems to work:

$(window).width() / parseFloat($("body").css("font-size"));
查看更多
爱情/是我丢掉的垃圾
5楼-- · 2020-05-16 20:17

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']
)
查看更多
再贱就再见
6楼-- · 2020-05-16 20:17

Simple, since we know 1em = 16px

var window_width_em = 1/16 * window_width_px;
查看更多
登录 后发表回答