Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

javascript - How can I get the font size of an element as it was set by css

I'm writing a simple jQuery that to change the font size of an element by a certain percentage. The problem I'm having is that when I get the size with jQuery's $('#el').css('font-size') it always returns a pixel value, even when set with em's. When I use Javscript's el.style.font-size property, it won't return a value until one has been explicitly set by the same property.

Is there some way I can get the original CSS set font-size value with Javascript? How cross-browser friendly is your method?

Thanks in advance!

Edit: I should note that all the tested browsers (See comment below) allow me to set the the text-size using an 'em' value using the two methods mentioned above, at which point the jQuery .css() returns an equivalent 'px' value and the Javascript .style.fontSize method returns the correct 'em' value. Perhaps the best way to do this would be to initialize the elements on page load, giving them an em value right away.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

All of your target browsers with the exception of IE will report to you the "Computed Style" of the element. In your case you don't want to know what the computed px size is for font-size, but rather you want the value set in your stylesheet(s).

Only IE can get this right with its currentStyle feature. Unfortunately jQuery in this case works against you and even gets IE to report the computed size in px (it uses this hack by Dean Edwards to do so, you can check the source yourself).

So in a nutshell, what you want is impossible cross-browser. Only IE can do it (provided you bypass jQuery to access the property). Your solution of setting the value inline (as opposed to in a stylesheet) is the best you can do, as then the browser does not need to compute anything.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...