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

我应该用什么?请包括浏览器兼容性信息。


当前回答

我为此创建了一个具有高度灵活性的效用函数:

export type Size = {width: number, height: number};
export enum GetSize_Method {
    /** Includes: content, padding. Excludes: border, margin, scroll-bar (if it has one), "position:absolute" descendants. */
    ClientSize = "ClientSize",
    /** Includes: content, padding, border, margin, scroll-bar (if it has one). Excludes: "position:absolute" descendants. */
    OffsetSize = "OffsetSize",
    /** Includes: content, padding, border, margin, scroll-bar (if it has one), "position:absolute" descendants. Excludes: none. */
    ScrollSize = "ScrollSize",
    /** Same as ScrollSize, except that it's calculated after the element's css transforms are applied. */
    BoundingClientRect = "BoundingClientRect",
    /** Lets you specify the exact list of components you want to include in the size calculation. */
    Custom = "Custom",
}
export type SizeComp = "content" | "padding" | "border" | "margin" | "scrollBar" | "posAbsDescendants";

export function GetSize(el: HTMLElement, method = GetSize_Method.ClientSize, custom_sizeComps?: SizeComp[]) {
    let size: Size;
    if (method == GetSize_Method.ClientSize) {
        size = {width: el.clientWidth, height: el.clientHeight};
    } else if (method == GetSize_Method.OffsetSize) {
        size = {width: el.offsetWidth, height: el.offsetHeight};
    } else if (method == GetSize_Method.ScrollSize) {
        size = {width: el.scrollWidth, height: el.scrollHeight};
    } else if (method == GetSize_Method.BoundingClientRect) {
        const rect = el.getBoundingClientRect();
        size = {width: rect.width, height: rect.height};
    } else if (method == GetSize_Method.Custom) {
        const style = window.getComputedStyle(el, null);
        const styleProp = (name: string)=>parseFloat(style.getPropertyValue(name));

        const padding = {w: styleProp("padding-left") + styleProp("padding-right"), h: styleProp("padding-top") + styleProp("padding-bottom")};
        const base = {w: el.clientWidth - padding.w, h: el.clientHeight - padding.h};
        const border = {w: styleProp("border-left") + styleProp("border-right"), h: styleProp("border-top") + styleProp("border-bottom")};
        const margin = {w: styleProp("margin-left") + styleProp("margin-right"), h: styleProp("margin-top") + styleProp("margin-bottom")};
        const scrollBar = {w: (el.offsetWidth - el.clientWidth) - border.w - margin.w, h: (el.offsetHeight - el.clientHeight) - border.h - margin.h};
        const posAbsDescendants = {w: el.scrollWidth - el.offsetWidth, h: el.scrollHeight - el.offsetHeight};

        const sc = (name: SizeComp, valIfEnabled: number)=>custom_sizeComps.includes(name) ? valIfEnabled : 0;
        size = {
            width: sc("content", base.w) + sc("padding", padding.w) + sc("border", border.w)
                    + sc("margin", margin.w) + sc("scrollBar", scrollBar.w) + sc("posAbsDescendants", posAbsDescendants.w),
            height: sc("content", base.h) + sc("padding", padding.h) + sc("border", border.h)
                    + sc("margin", margin.h) + sc("scrollBar", scrollBar.h) + sc("posAbsDescendants", posAbsDescendants.h),
        };
    }
    return size;
}

用法:

const el = document.querySelector(".my-element");
console.log("Size:", GetSize(el, "ClientSize"));
console.log("Size:", GetSize(el, "Custom", ["content", "padding", "border"]));

其他回答

根据MDN:确定元素的尺寸

offsetWidth和offsetHeight返回“一个元素占用的空间总量,包括可见内容的宽度、滚动条(如果有的话)、填充和边框”

clientWidth和clienttheight返回“实际显示内容占用的空间大小,包括填充,但不包括边框、页边距或滚动条”

scrollWidth和scrollHeight返回“内容的实际大小,不管当前有多少可见”

因此,这取决于所测量的内容是否预计在当前可视区域之外。

使用width参数如下:

   style={{
      width: "80%",
      paddingLeft: 100,
      paddingRight: 200,
      paddingTop: 30,
      paddingBottom: 30,
      border: "3px solid lightGray",
    }}

元素。offsetWidth和元素。offsetHeight应该这样做,就像在之前的帖子中建议的那样。

但是,如果您只想集中内容,还有更好的方法。假设您使用严格的xhtml DOCTYPE。设置body标签的margin:0,auto属性和所需宽度(px)。内容与页面居中对齐。

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

JavaScript不能读取任何来自css(内部/外部)的元素样式属性(element .style),除非你在JavaScript中使用内置方法调用getComputedStyle。

getComputedStyle(元素(伪)

元素:要读取其值的元素。 伪元素,如果需要,例如::before。空字符串或无参数表示元素本身。

结果是一个具有样式属性的对象,如elem。样式,但现在是关于所有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);
    }

}

计算和解析值

CSS中有两个概念:

计算出的样式值是所有CSS规则和CSS之后的值 继承被应用,作为CSS级联的结果。它看起来 比如高度:1em或字体大小:125%。 已解析的样式值是最终应用于元素的样式值。 1em或125%这样的值是相对的。浏览器接受计算结果 值并使所有单位固定和绝对,例如: 高度:20px或字体大小:16px。用于几何属性解析值 可以有一个浮点数,比如width:50.5px。

很久以前创建了getComputedStyle来获取计算值,但后来发现解析值要方便得多,因此标准发生了变化。 现在getComputedStyle实际上返回属性的解析值。

请注意:

getComputedStyle需要完整的属性名

你应该总是要你想要的东西,比如 左,高,宽。否则正确的 结果不保证。 例如,如果有属性paddingLeft/paddingTop,那么 我们应该为getComputedStyle(elem).padding获取什么?什么,或 也许是从已知填充中“生成”的值?没有标准 规则在这里。

还有其他不一致之处。例如,一些浏览器(Chrome)在下面的文档中显示10px,而其中一些(Firefox) -不显示:

<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

Flex

如果你想在<div>中显示屏幕中心的某种弹出消息,那么你不需要读取<div>的大小,但你可以使用flex

.box { 宽度:50 px; 高度:20 px; 背景:红色; } .container { 显示:flex; justify-content:中心; 对齐项目:中心; 身高:100 vh; 宽度:100大众; 位置:固定;/*如果div下没有内容,则删除它(并且记住将正文边距设置为0)*/ } < div class = "容器" > <div class="box">我的div</div> < / div >