¿Cómo encontrar el ancho de un div usando JavaScript raw?


¿Cómo se encuentra el ancho actual de un <div> de una manera compatible con varios navegadores sin utilizando una biblioteca como jQuery?

Author: Xufox, 2011-01-25

7 answers

document.getElementById("mydiv").offsetWidth
 312
Author: Andy E,
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
2016-07-11 08:06:47

Puede usar clientWidth o offsetWidth Referencia de la red de desarrolladores de Mozilla

Sería como:

document.getElementById("yourDiv").clientWidth; // returns number, like 728

O con ancho de bordes:

document.getElementById("yourDiv").offsetWidth; // 728 + borders width
 28
Author: khrizenriquez,
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-11-27 21:14:52

Todas las respuestas son correctas, pero todavía quiero dar algunas otras alternativas que pueden funcionar.

Si está buscando el ancho asignado (ignorando el relleno, el margen, etc.), podría usarlo.

getComputedStyle(element).width; //returns value in px like "727.7px"

GetComputedStyle le permite acceder a todos los estilos de esos elementos. Por ejemplo: padding, paddingLeft, margin, border-top-left-radius y así sucesivamente.

 7
Author: Alex Flexlex Waldboth,
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-04-21 21:29:40

También puede buscar en el DOM usando className. Por ejemplo:

document.getElementsByClassName("myDiv")

Esto devolverá un array. Si hay una propiedad en particular que le interesa. Por ejemplo:

var divWidth = document.getElementsByClassName("myDiv")[0].clientWidth;

divWidth ahora será igual al ancho del primer elemento en su matriz div.

 2
Author: user3386050,
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
2015-11-04 11:07:31

En realidad, no tienes que usar document.getElementById("mydiv").
Simplemente puede usar el id del div, como:

var w = mydiv.clientWidth;
o
var w = mydiv.offsetWidth;
sucesivamente.

 1
Author: Ari,
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-10-07 10:36:05

Llame al método siguiente en div o etiqueta de cuerpo onclick = " show (event);" función show (event) {

        var x = event.clientX;
        var y = event.clientY;

        var ele = document.getElementById("tt");
        var width = ele.offsetWidth;
        var height = ele.offsetHeight;
        var half=(width/2);
       if(x>half)
        {
          //  alert('right click');
            gallery.next();
        }
        else
       {
           //   alert('left click');
            gallery.prev();
        }


    }
 0
Author: Amrik,
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
2015-06-11 21:46:31

La forma correcta de obtener el estilo calculado es esperar hasta que se renderice la página. Se puede hacer de la siguiente manera. Preste atención al tiempo de espera al obtener los valores auto.

function getStyleInfo() {
    setTimeout(function() {
        const style = window.getComputedStyle(document.getElementById('__root__'));
        if (style.height == 'auto') {
            getStyleInfo();
        }
        // IF we got here we can do actual business logic staff
        console.log(style.height, style.width);
    }, 100);
};

window.onload=function() { getStyleInfo(); };

Si usa solo

window.onload=function() {
    var computedStyle = window.getComputedStyle(document.getElementById('__root__'));
}

Puede obtener auto valores para width y height porque los navegadores no se renderizan hasta que se realiza la carga completa.

 0
Author: Siarhei Kuchuk,
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
2018-03-28 12:52:46