如何保证元素具有特定的高度 [英] How to guarantee an element will have a particular height

查看:68
本文介绍了如何保证元素具有特定的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我的页面上有这个元素:

Say that I have this element on my page:

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

我想使用JavaScript测量div的高度,以找出该元素等于1em的像素数.

I want to use JavaScript to measure the height of the div to figure out how many px are equivalent to 1em for that element.

所以,如果我这样做了:

So if I did:

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

那我可能会得到16.

但是,如果用户可以在此网页上注入任意样式,该怎么办?如果他们做类似的事情怎么办?

But what if users can inject arbitrary styles onto this webpage? What if they do something like:

div { border: 1px solid black; }

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

Then I would get 18, because of the unexpected border applied to all div elements.

为避免这种情况,我可以在div中添加样式清单,以删除潜在的意外样式:"

To avoid this, I could add a laundry list of styles to the div to remove potential "unexpected styles:"

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

但是,样式列表是否全面?如果没有,我还需要其他哪些样式?还是有更好的方法进行计算?

But is that list of styles comprehensive? If not, what other styles do I need? Or is there a better way to make this calculation?

推荐答案

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

Set the font-style: 1em !important; on the element, and get the font size in px using Window#getComputedStyle:

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

console.log(fontSize);

<div id="div" style="font-size: 1em;"></div>

我先前的非防弹答案:

如果用户使用高度大于16的边框和/或填充,则此操作将失败.

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

You can use box-sizing: border-box on the element. With this box sizing, the borders and the paddings don't increase the dimensions of the element. The content area is the original width/height minus any paddings and borders.

console.log(div.getBoundingClientRect().height);

div {
  padding: 3px;
  border: 2px solid black;
}

<div id="div" style="height: 1em; box-sizing: border-box;">

这篇关于如何保证元素具有特定的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆