[removed] convert ex to px

后端 未结 2 1169
面向向阳花
面向向阳花 2021-01-22 06:42

So I\'m reading elem.style.width, and getting something like \"3.1415926ex\".

I would like to convert this to \"px.\"

Does JavaScript have built in functions to

2条回答
  •  忘掉有多难
    2021-01-22 06:58

    There is no built-in function for the purpose. Given an element that is accessible in JavaScript using the variable elem, you can get its width in pixels, rounded to an integer, using the expression elem.clientWidth. To get it as unrounded, with precision varying by browser, you can in principle use elem.getBoundingClientRect().width instead, though it will in practice yield a rounded result or an inaccurate result in many browsers. – This applies if the horizontal padding of the element is zero.

    If you set, say, the width of an element to 1ex and then apply the above to it, you will get an integer or a real number that tells you the value of ex in pixels. But it’s not a magic constant: it depends on the font family and on the font size.

    Note: Some old browsers, such as IE 7, incorrectly implement the ex unit just as half of the em unit, instead of properly using the x-height of the font.

提交回复
热议问题