首页 文章

如何检索HTML元素的实际宽度和高度?

提问于
浏览
685

假设我有一个 <div> ,我希望在浏览器的显示(视口)中居中 . 为此,我需要计算 <div> 元素的宽度和高度 .

我该怎么用?请包含有关浏览器兼容性的信息

12 回答

  • 0

    您应该使用 .offsetWidth.offsetHeight 属性 . 注意它们属于元素,而不是 .style .

    var width = document.getElementById('foo').offsetWidth;

  • 34

    这是 WKWebView 的代码,它决定了特定Dom元素的高度(对整个页面不起作用)

    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 {
    
            }
        }
    }
    
  • 1

    如前一篇文章所述,element.offsetWidth和element.offsetHeight应该这样做 .

    但是,如果您只想将内容集中在一起,那么有一种更好的方法 . 假设您使用xhtml strict DOCTYPE . 设置margin:0,自动属性和px中所需的宽度到body标签 . 内容与页面对齐 .

  • 57

    ...似乎CSS帮助将div放在中心...

    <style>
     .monitor {
     position:fixed;/* ... absolute possible if on :root */
     top:0;bottom:0;right:0;left:0;
     visibility:hidden;
     }
     .wrapper {
     width:200px;/* this is size range */
     height:100px;
     position:absolute;
     left:50%;top:50%;
     visibility:hidden;
     }
    
     .content {
     position:absolute;
     width: 100%;height:100%;
     left:-50%;top:-50%;
     visibility:visible;
     }
    
    </style>
    
     <div class="monitor">
      <div class="wrapper">
       <div class="content">
    
     ... so you hav div 200px*100px on center ...
    
      </div>
     </div>
    </div>
    
  • 1028

    NOTE :这个答案写于2008年 . 当时大多数人最好的跨浏览器解决方案就是使用jQuery . 我'm leaving the answer here for posterity and, if you'重新使用jQuery,这是一个很好的方法 . 如果您正在使用其他框架或纯JavaScript,那么接受的答案可能就是您的选择 .

    从jQuery 1.2.6开始,您可以使用核心CSS functionsheightwidth (或者 outerHeightouterWidth ,视情况而定) .

    var height = $("#myDiv").height();
    var width = $("#myDiv").width();
    
    var docHeight = $(document).height();
    var docWidth = $(document).width();
    
  • 1

    为了防止对任何人有用,我把一个文本框,按钮和div都放在同一个css中:

    width:200px;
    height:20px;
    border:solid 1px #000;
    padding:2px;
    
    <input id="t" type="text" />
    <input id="b" type="button" />
    <div   id="d"></div>
    

    我尝试使用chrome,firefox和ie-edge,我尝试使用jquery而没有,我尝试使用和不使用 box-sizing:border-box . 始终与 <!DOCTYPE html>

    结果:

    Firefox       Chrome        IE-Edge    
                                                                  with   w/o    with   w/o    with   w/o     box-sizing
    
    $("#t").width()                                               194    200    194    200    194    200
    $("#b").width()                                               194    194    194    194    194    194
    $("#d").width()                                               194    200    194    200    194    200
    
    $("#t").outerWidth()                                          200    206    200    206    200    206
    $("#b").outerWidth()                                          200    200    200    200    200    200
    $("#d").outerWidth()                                          200    206    200    206    200    206
    
    $("#t").innerWidth()                                          198    204    198    204    198    204
    $("#b").innerWidth()                                          198    198    198    198    198    198
    $("#d").innerWidth()                                          198    204    198    204    198    204
    
    $("#t").css('width')                                          200px  200px  200px  200px  200px  200px
    $("#b").css('width')                                          200px  200px  200px  200px  200px  200px
    $("#d").css('width')                                          200px  200px  200px  200px  200px  200px
    
    $("#t").css('border-left-width')                              1px    1px    1px    1px    1px    1px
    $("#b").css('border-left-width')                              1px    1px    1px    1px    1px    1px
    $("#d").css('border-left-width')                              1px    1px    1px    1px    1px    1px
    
    $("#t").css('padding-left')                                   2px    2px    2px    2px    2px    2px
    $("#b").css('padding-left')                                   2px    2px    2px    2px    2px    2px
    $("#d").css('padding-left')                                   2px    2px    2px    2px    2px    2px
    
    document.getElementById("t").getBoundingClientRect().width    200    206    200    206    200    206
    document.getElementById("b").getBoundingClientRect().width    200    200    200    200    200    200
    document.getElementById("d").getBoundingClientRect().width    200    206    200    206    200    206
    
    document.getElementById("t").offsetWidth                      200    206    200    206    200    206
    document.getElementById("b").offsetWidth                      200    200    200    200    200    200
    document.getElementById("d").offsetWidth                      200    206    200    206    200    206
    
  • 4

    修改元素样式很容易,但读取值有点棘手 .

    JavaScript无法读取来自css(内部/外部)的任何元素样式属性(elem.style),除非您在javascript中使用内置方法调用getComputedStyle .

    getComputedStyle(element [,pseudo])

    Element: 要读取值的元素 .
    pseudo: 如果需要,则为伪元素,例如:: before . 空字符串或无参数表示元素本身 .

    结果是一个具有样式属性的对象,如elem.style,但现在关于所有css类 .

    例如,这里的样式没有看到边距:

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

    因此修改了您的javaScript代码以包含您希望获得它的宽度/高度或其他属性的元素的getComputedStyle

    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

    CSS中有两个概念:

    计算样式值是应用所有CSS规则和CSS继承之后的值,作为CSS级联的结果 . 它看起来像高度:1em或字体大小:125% . 已解析的样式值是最终应用于元素的样式值 . 像1em或125%这样的值是相对的 . 浏览器获取计算值并使所有单位固定且绝对,例如:height:20px或font-size:16px . 对于几何属性,已解析值可能具有浮点,如宽度:50.5px .

    很久以前创建了getComputedStyle来获取计算值,但事实证明,解析的值更方便,标准也发生了变化 .
    所以现在getComputedStyle实际上返回了属性的已解析值 .

    Please Note:

    getComputedStyle requires the full property name

    您应该始终询问您想要的确切属性,例如paddingLeft或height或width . 否则,无法保证正确的结果 . 例如,如果有属性paddingLeft / paddingTop,那么getComputedStyle(elem).padding应该得到什么?没有什么,或者可能是已知填充的“生成”值?这里没有标准规则 .

    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>
    

    了解更多信息https://javascript.info/styles-and-classes

  • 6

    您只需要为IE7及更早版本计算它(并且仅当您的内容没有固定大小时) . 我建议使用HTML条件注释来限制不支持CSS2的旧IE . 对于所有其他浏览器使用此:

    <style type="text/css">
        html,body {display:table; height:100%;width:100%;margin:0;padding:0;}
        body {display:table-cell; vertical-align:middle;}
        div {display:table; margin:0 auto; background:red;}
    </style>
    <body><div>test<br>test</div></body>
    

    这是完美的解决方案 . 它以任何大小的 <div> 为中心,并将其缩小到其内容的大小 .

  • 130

    如果offsetWidth返回0,则可以获取元素的样式宽度属性并在其中搜索数字 . “100px” - > 100

    /\d*/.exec(MyElement.style.width)

  • -3

    看看Element.getBoundingClientRect() .

    此方法将返回包含 widthheight 和其他一些有用值的对象:

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

    例如:

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

    我相信这不会有 .offsetWidth.offsetHeight 在有时会返回 0 的问题(如_466020中所述)

    另一个区别是 getBoundingClientRect() 可能返回小数像素,其中 .offsetWidth.offsetHeight 将舍入到最接近的整数 .

    IE8 NotegetBoundingClientRect 不会在 IE8 及以下返回高度和宽度 . *

    如果必须支持IE8,请使用 .offsetWidth.offsetHeight

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

    值得注意的是,此方法返回的Object实际上并不是一个普通的对象 . 它的属性不是enumerable(例如, Object.keys 不起作用盒子外面 . )

    更多信息:How best to convert a ClientRect / DomRect into a plain Object

    参考:

  • 1

    根据MDN: Determining the dimensions of elements

    offsetWidthoffsetHeight 返回"total amount of space an element occupies, including the width of the visible content, scrollbars (if any), padding, and border"

    clientWidthclientHeight 返回"how much space the actual displayed content takes up, including padding but not including the border, margins, or scrollbars"

    scrollWidthscrollHeight 返回"actual size of the content, regardless of how much of it is currently visible"

    因此,这取决于预计测量的内容是否超出当前可视区域 .

  • 0

    你也可以使用这段代码:

    var divID = document.getElementById("divid");
    
    var h = divID.style.pixelHeight;
    

相关问题