How do I retrieve an HTML element's actual width and height?

前端 未结 14 1816
后悔当初
后悔当初 2020-11-22 02:29

Suppose that I have a

that I wish to center in the browser\'s display (viewport). To do so, I need to calculate the width and height of the &l
14条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 03:03

    Take a look at Element.getBoundingClientRect().

    This method will return an object containing the width, height, and some other useful values:

    {
        width: 960,
        height: 71,
        top: 603,
        bottom: 674,
        left: 360,
        right: 1320
    }
    

    For Example:

    var element = document.getElementById('foo');
    var positionInfo = element.getBoundingClientRect();
    var height = positionInfo.height;
    var width = positionInfo.width;
    

    I believe this does not have the issues that .offsetWidth and .offsetHeight do where they sometimes return 0 (as discussed in the comments here)

    Another difference is getBoundingClientRect() may return fractional pixels, where .offsetWidth and .offsetHeight will round to the nearest integer.

    IE8 Note: getBoundingClientRect does not return height and width on IE8 and below.*

    If you must support IE8, use .offsetWidth and .offsetHeight:

    var height = element.offsetHeight;
    var width = element.offsetWidth;
    

    Its worth noting that the Object returned by this method is not really a normal object. Its properties are not enumerable (so, for example, Object.keys doesn't work out-of-the-box.)

    More info on this here: How best to convert a ClientRect / DomRect into a plain Object

    Reference:

    • .offsetHeight: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetHeight
    • .offsetWidth: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetWidth
    • .getBoundingClientRect(): https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect

提交回复
热议问题