假设我有一个<div>
我希望在浏览器的显示(视口)中居中。为此,我需要计算<div>
元素的宽度和高度。
我应该使用什么?请提供有关浏览器兼容性的信息。
答案 0 :(得分:1119)
您应该使用.offsetWidth
和.offsetHeight
属性。
请注意,它们属于元素,而不是.style
。
var width = document.getElementById('foo').offsetWidth;
答案 1 :(得分:156)
看看Element.getBoundingClientRect()
。
此方法将返回包含width
,height
和其他一些有用值的对象:
{
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
的问题(如comments here中所述)
另一个区别是getBoundingClientRect()
可能会返回小数像素,其中.offsetWidth
和.offsetHeight
会舍入到最接近的整数。
IE8注意:getBoundingClientRect
不会在 IE8 及以下返回高度和宽度。*
如果必须支持IE8,请使用.offsetWidth
和.offsetHeight
:
var height = element.offsetHeight;
var width = element.offsetWidth;
值得注意的是,此方法返回的Object实际上并不是 normal 对象。它的属性不是enumerable(因此,例如,Object.keys
并不是开箱即用的。)
此处有关于此的更多信息: How best to convert a ClientRect / DomRect into a plain Object
参考:
.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 答案 2 :(得分:59)
注意:这个答案写于2008年。当时大多数人最好的跨浏览器解决方案就是使用jQuery。我将这里的答案留给后人,如果你使用的是jQuery,这是一个很好的方法。如果你正在使用其他框架或纯JavaScript,那么接受的答案可能就是你想要的。
从jQuery 1.2.6开始,您可以根据需要使用核心CSS functions,height
和width
(或outerHeight
和outerWidth
之一)
var height = $("#myDiv").height();
var width = $("#myDiv").width();
var docHeight = $(document).height();
var docWidth = $(document).width();
答案 3 :(得分:37)
以防它对任何人都有用,我把一个文本框,按钮和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 :(得分:12)
根据MDN: Determining the dimensions of elements
offsetWidth
和offsetHeight
返回&#34;元素占用的总空间量,包括可见内容的宽度,滚动条(如果有),填充和边框&#34; < / p>
clientWidth
和clientHeight
返回&#34;实际显示的内容占用了多少空间,包括填充但不包括边框,边距或滚动条&#34;
scrollWidth
和scrollHeight
会返回&#34;内容的实际大小,无论目前有多少内容可见#34;
因此,这取决于预计测量的内容是否超出当前可见区域。
答案 5 :(得分:4)
您只需要为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>
为中心,并将其缩小到其内容的大小。
答案 6 :(得分:2)
修改元素样式很容易,但读取值有点棘手。
JavaScript无法读取来自css(内部/外部)的任何元素样式属性(elem.style),除非您在javascript中使用内置方法调用getComputedStyle。
getComputedStyle(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&#39;的宽度/高度或其他属性
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。对于几何属性已解析的值 可能有一个浮点,如宽度:50.5px。
很久以前创建了getComputedStyle来获取计算值,但事实证明,解析后的值更方便,标准也发生了变化。
所以现在getComputedStyle实际上返回了属性的已解析值。
请注意:
getComputedStyle需要完整的属性名称
你应该总是询问你想要的确切财产,比如 paddingLeft或高度或宽度。否则是正确的 结果无法保证。
例如,如果有属性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>
答案 7 :(得分:1)
element.offsetWidth和element.offsetHeight应如前所述。
但是,如果您只想将内容集中在一起,那么有一种更好的方法。假设您使用xhtml strict DOCTYPE。设置margin:0,自动属性和px中所需的宽度到body标签。内容与页面对齐。
答案 8 :(得分:1)
...似乎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>
答案 9 :(得分:0)
你也可以使用这段代码:
var divID = document.getElementById("divid");
var h = divID.style.pixelHeight;
答案 10 :(得分:0)
如果需要在浏览器的显示端口中居中;您只能使用CSS来实现
yourSelector {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
答案 11 :(得分:0)
如果您想在屏幕中心显示<div>
的某种弹出消息-那么您无需读取<div>
的大小,但可以使用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>
答案 12 :(得分:0)
按如下所示使用width参数:
style={{
width: "80%",
paddingLeft: 100,
paddingRight: 200,
paddingTop: 30,
paddingBottom: 30,
border: "3px solid lightGray",
}}
答案 13 :(得分:0)
我为此创建了一个实用函数,具有很高的灵活性:
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"]));
答案 14 :(得分:-1)
以下是 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 {
}
}
}
答案 15 :(得分:-3)
如果offsetWidth返回0,则可以获取元素的样式宽度属性并在其中搜索数字。 &#34; 100像素&#34; - &GT; 100
/ \ d * /。EXEC(MyElement.style.width)