¿Es posible obtener el ancho de la ventana en unidades em usando javascript?


Estoy buscando una manera confiable de obtener el ancho de la ventana en unidades em usando javascript. Me sorprendió ver que jQuery solo devolverá un resultado en mediciones de píxeles. Cualquier ayuda es apreciada.

Author: hammerbrostime, 2012-09-03

5 answers

Esto parece funcionar:

$(window).width() / parseFloat($("body").css("font-size"));
 46
Author: hammerbrostime,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-03 02:26:20

Aquí hay una solución que no requiere jQuery, y no requiere una declaración explícita de tamaño de fuente.

window.innerWidth /
  parseFloat(getComputedStyle(document.querySelector('body'))['font-size'])
 16
Author: Brad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-06 06:07:32

Para aquellos que lo necesitan todo junto, este código funciona para mí:

<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>

Se pone junto usando la respuesta anterior agregada al código de prueba window-width que se encuentra en el tutorial vinculado.

 1
Author: bofa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-16 17:00:54

Es posible calcularlo, pero em no es una unidad "simple" como px porque depende de una selección de fuente (es decir, una combinación de familia de fuente, estilo (negrita, cursiva, etc.) y tamaño de fuente). Por supuesto, el tamaño de la fuente en sí puede ser relativo (por ejemplo, si em, ex, o tamaño porcentual, entonces la altura calculada px para esa fuente se deriva del tamaño del elemento padre).

Para obtener el ancho em de una página, puede hacer la conversión de esta manera (advertencia: 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
Author: Dai,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-03 02:26:42

Simple, ya que sabemos 1em = 16px

var window_width_em = 1/16 * window_width_px;
 -16
Author: Rezigned,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-03 03:58:22