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

前端 未结 14 1680
后悔当初
后悔当初 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 02:58

    NOTE: this answer was written in 2008. At the time the best cross-browser solution for most people really was to use jQuery. I'm leaving the answer here for posterity and, if you're using jQuery, this is a good way to do it. If you're using some other framework or pure JavaScript the accepted answer is probably the way to go.

    As of jQuery 1.2.6 you can use one of the core CSS functions, height and width (or outerHeight and outerWidth, as appropriate).

    var height = $("#myDiv").height();
    var width = $("#myDiv").width();
    
    var docHeight = $(document).height();
    var docWidth = $(document).width();
    
    0 讨论(0)
  • 2020-11-22 02:58

    Flex

    In case that you want to display in your <div> some kind of popUp message on screen center - then you don't need to read size of <div> but you can use flex

    .box {
      width: 50px;
      height: 20px;
      background: red;
    }
    
    .container {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      width: 100vw;
      position: fixed; /* remove this in case there is no content under div (and remember to set body margins to 0)*/
    }
    <div class="container">
      <div class="box">My div</div>
    </div>

    0 讨论(0)
  • 2020-11-22 02:59

    According to MDN: Determining the dimensions of elements

    offsetWidth and offsetHeight return the "total amount of space an element occupies, including the width of the visible content, scrollbars (if any), padding, and border"

    clientWidth and clientHeight return "how much space the actual displayed content takes up, including padding but not including the border, margins, or scrollbars"

    scrollWidth and scrollHeight return the "actual size of the content, regardless of how much of it is currently visible"

    So it depends on whether the measured content is expected to be out of the current viewable area.

    0 讨论(0)
  • 2020-11-22 03:00

    It is easy to modify the elements styles but kinda tricky to read the value.

    JavaScript can't read any element style property (elem.style) coming from css(internal/external) unless you use the built in method call getComputedStyle in javascript.

    getComputedStyle(element[, pseudo])

    Element: The element to read the value for.
    pseudo: A pseudo-element if required, for instance ::before. An empty string or no argument means the element itself.

    The result is an object with style properties, like elem.style, but now with respect to all css classes.

    For instance, here style doesn’t see the margin:

    <head>
      <style> body { color: red; margin: 5px } </style>
    </head>
    <body>
    
      <script>
        let computedStyle = getComputedStyle(document.body);
    
        // now we can read the margin and the color from it
    
        alert( computedStyle.marginTop ); // 5px
        alert( computedStyle.color ); // rgb(255, 0, 0)
      </script>
    
    </body>
    

    So modified your javaScript code to include the getComputedStyle of the element you wish to get it's width/height or other attribute

    window.onload = function() {
    
        var test = document.getElementById("test");
        test.addEventListener("click", select);
    
    
        function select(e) {                                  
            var elementID = e.target.id;
            var element = document.getElementById(elementID);
            let computedStyle = getComputedStyle(element);
            var width = computedStyle.width;
            console.log(element);
            console.log(width);
        }
    
    }
    

    Computed and resolved values

    There are two concepts in CSS:

    A computed style value is the value after all CSS rules and CSS inheritance is applied, as the result of the CSS cascade. It can look like height:1em or font-size:125%.

    A resolved style value is the one finally applied to the element. Values like 1em or 125% are relative. The browser takes the computed value and makes all units fixed and absolute, for instance: height:20px or font-size:16px. For geometry properties resolved values may have a floating point, like width:50.5px.

    A long time ago getComputedStyle was created to get computed values, but it turned out that resolved values are much more convenient, and the standard changed.
    So nowadays getComputedStyle actually returns the resolved value of the property.

    Please Note:

    getComputedStyle requires the full property name

    You should always ask for the exact property that you want, like paddingLeft or height or width. Otherwise the correct result is not guaranteed.

    For instance, if there are properties paddingLeft/paddingTop, then what should we get for getComputedStyle(elem).padding? Nothing, or maybe a “generated” value from known paddings? There’s no standard rule here.

    There are other inconsistencies. As an example, some browsers (Chrome) show 10px in the document below, and some of them (Firefox) – do not:

    <style>
      body {
        margin: 30px;
        height: 900px;
      }
    </style>
    <script>
      let style = getComputedStyle(document.body);
      alert(style.margin); // empty string in Firefox
    </script>
    

    for more information https://javascript.info/styles-and-classes

    0 讨论(0)
  • 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
    0 讨论(0)
  • 2020-11-22 03:06

    Here is the code for WKWebView what determines a height of specific Dom element (doesn't work properly for whole page)

    let html = "<body><span id=\"spanEl\" style=\"font-family: '\(taskFont.fontName)'; font-size: \(taskFont.pointSize - 4.0)pt; color: rgb(\(red), \(blue), \(green))\">\(textValue)</span></body>"
    webView.navigationDelegate = self
    webView.loadHTMLString(taskHTML, baseURL: nil)
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        webView.evaluateJavaScript("document.getElementById(\"spanEl\").getBoundingClientRect().height;") { [weak self] (response, error) in
            if let nValue = response as? NSNumber {
    
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题