问题
Say that I have this element on my page:
<div style="height: 1em;"> </div>
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()
Then I might get 16
.
But what if users can inject arbitrary styles onto this webpage? What if they do something like:
div { border: 1px solid black; }
Then I would get 18
, because of the unexpected border applied to all div
elements.
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;"> </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?
回答1:
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>
My previous not bullet proof answer:
This fails if the user uses borders and/or paddings which height is greater than 16.
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;">
来源:https://stackoverflow.com/questions/46739264/how-to-guarantee-an-element-will-have-a-particular-height