How to find the width of a div using vanilla JavaScript?

前端 未结 8 1207
遥遥无期
遥遥无期 2020-11-27 10:19

How do you find the current width of a

in a cross-browser compatible way without using a library like jQuery?

相关标签:
8条回答
  • 2020-11-27 11:03

    The correct way of getting computed style is waiting till page is rendered. It can be done in the following manner. Pay attention to timeout on getting auto values.

    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(); };
    

    If you use just

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

    you can get auto values for width and height because browsers does not render till full load is performed.

    0 讨论(0)
  • 2020-11-27 11:08

    You can use clientWidth or offsetWidth Mozilla developer network reference

    It would be like:

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

    or with borders width :

    document.getElementById("yourDiv").offsetWidth; // 728 + borders width
    
    0 讨论(0)
提交回复
热议问题