假设我有一个<div>,我希望它位于浏览器显示(视口)的中央。为此,我需要计算<div>元素的宽度和高度。
我应该用什么?请包括浏览器兼容性信息。
假设我有一个<div>,我希望它位于浏览器显示(视口)的中央。为此,我需要计算<div>元素的宽度和高度。
我应该用什么?请包括浏览器兼容性信息。
当前回答
这是唯一对我有效的方法:
element.clientWidth -
parseFloat(window.getComputedStyle(element, null).getPropertyValue("padding-left")) -
parseFloat(window.getComputedStyle(element, null).getPropertyValue("padding-right"))
其他回答
下面是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 {
}
}
}
我为此创建了一个具有高度灵活性的效用函数:
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"]));
注:这个答案写于2008年。当时,对于大多数人来说,最好的跨浏览器解决方案就是使用jQuery。我把答案留给后人,如果您正在使用jQuery,这是一个很好的方法。如果您正在使用其他框架或纯JavaScript,那么接受的答案可能是正确的。
从jQuery 1.2.6开始,你可以使用CSS的核心函数之一,height和width(或者outerHeight和outerWidth,视情况而定)。
var height = $("#myDiv").height();
var width = $("#myDiv").width();
var docHeight = $(document).height();
var docWidth = $(document).width();
以防它对任何人都有用,我把一个文本框,按钮和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
你应该使用. offsetwidth和. offsetheight属性。 注意它们属于元素,而不是.style。
var width = document.getElementById('foo').offsetWidth;
. getboundingclientrect()函数的作用是:在执行CSS转换后,以浮点数的形式返回元素的尺寸和位置。
> console.log(document.getElementById('foo').getBoundingClientRect())
DOMRect {
bottom: 177,
height: 54.7,
left: 278.5,
right: 909.5,
top: 122.3,
width: 631,
x: 278.5,
y: 122.3,
}