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

前端 未结 5 1799
误落风尘
误落风尘 2021-01-31 14:55

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.

相关标签:
5条回答
  • 2021-01-31 14:59

    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.

    0 讨论(0)
  • 2021-01-31 15:09

    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']
    )
    
    0 讨论(0)
  • 2021-01-31 15:09

    Simple, since we know 1em = 16px

    var window_width_em = 1/16 * window_width_px;
    
    0 讨论(0)
  • 2021-01-31 15:10

    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;
    }
    
    0 讨论(0)
  • 2021-01-31 15:15

    This seems to work:

    $(window).width() / parseFloat($("body").css("font-size"));
    
    0 讨论(0)
提交回复
热议问题