JavaScript: convert ex to px - Stack Overflow

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

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 do this? I'd prefer that chopping off last 2 letters of string, reading it as a number, and multiplying it by a magic constant.

Thanks!

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 do this? I'd prefer that chopping off last 2 letters of string, reading it as a number, and multiplying it by a magic constant.

Thanks!

Share Improve this question asked Sep 18, 2012 at 5:36 user1647794user1647794 1
  • Nope, no built-in conversion function. – Felix Kling Commented Sep 18, 2012 at 5:37
Add a ment  | 

2 Answers 2

Reset to default 5

There is no "magic constant" because there is no straight-forward conversion from ex to px (unlike, say, converting inches to centimetres).

An ex unit is the height of the lowercase 'x' character in the current font (where a "font" is a bination of typeface family (e.g. Times New Roman), size (say, 14px or 72pt), and style (regular, bold, italic)).

...so "1ex" in 72pt Impact Bold is larger than "1ex" in 8pt Helvetica Regular.

Converting from ex to px can be done if you know these details. Of course, it sounds like you really just want the "puted style", which is always in pixels. Read this: How do I get a puted style?

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742350057a4427331.html

相关推荐

  • JavaScript: convert ex to px - Stack Overflow

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

    2小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信