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

前端 未结 5 1800
误落风尘
误落风尘 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 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;
    }
    

提交回复
热议问题