如何保证一个元素有一个特定的高度

How to guarantee an element will have a particular height

假设我的页面上有这个元素:

<div style="height: 1em;">&nbsp;</div>

我想使用 JavaScript 来测量 div 的高度,以计算出该元素有多少像素等于 1em。

如果我这样做了:

document.querySelector('div').getBoundingClientRect()

那我可能会得到16.

但是如果用户可以将任意样式注入到这个网页上呢?如果他们做类似的事情怎么办:

div { border: 1px solid black; }

然后我会得到 18,因为意外的边框应用于所有 div 元素。

为了避免这种情况,我可以在 div 中添加一份样式清单,以消除潜在的 "unexpected styles:"

<div style="border: 0; margin: 0; padding: 0; height: 1em;">&nbsp;</div>

但是这个样式列表是否全面?如果没有,我还需要什么其他样式?或者有更好的计算方法吗?

在元素上设置 font-style: 1em !important;,并使用 Window#getComputedStyle:

获取 px 中的字体大小

var fontSize = window.getComputedStyle(div).fontSize;

console.log(fontSize);
<div id="div" style="font-size: 1em;"></div>

我之前的非防弹答案:

如果用户使用高度大于 16 的边框 and/or 填充,则此操作失败。

您可以在元素上使用 box-sizing: border-box。使用此框大小,边框和填充不会增加元素的尺寸。内容区域是原始的 width/height 减去 任何填充和边框。

console.log(div.getBoundingClientRect().height);
div {
  padding: 3px;
  border: 2px solid black;
}
<div id="div" style="height: 1em; box-sizing: border-box;">