问题
I find the following JS solution to having text resize based on viewport size quite elegant:
https://stackoverflow.com/a/10295733/1318135
onresize=onload=function(){document.body.style.fontSize=window.innerWidth+"px"}
However, there are 2 issues:
It relies on the viewport being resized. I'd like to trigger it when the page is first loaded as well, but am a newb at JS.
My page is coded entirely using em values; this uses px. How can I use this to adjust the default em size only which will then automatically trickle down to every other element on the page?
http://jsfiddle.net/hFNc7/
Thanks!
回答1:
See other answer (or put http://jsfiddle.net/cjzEK/1/ on the bottom of your page)
em is not a size on its own. It's a percentage written differently. The only way em works for you is because there is 1 base font-size that is set in the browser(or also likely a reset stylesheet). The usual base size of fonts in browsers is 16px. So what this solution does is changing the base size by adding it to the body(adding it to the html might be even better).
e.g. p{font-size:1em;} without any reset done will be 16px. 1.5em will be 24px.
回答2:
You need to run that code in the body's load event. Easiest way to do so is setting it directy through its onload attribute:
<body onload="var f = function () { document.body.style.fontSize = 0.2 * window.innerWidth + 'px'; }; window.onresize = f; f();">
What it does:
- Creates a function, that is able to set the font size dynamically.
- Sets the function as
resizeevent listener. - Execute the function instantly.
PS: There are more elegant ways to write this, but since your new, it might be better to start with an easier notation.
来源:https://stackoverflow.com/questions/11798926/tweaking-performance-of-elegant-solution-to-text-resize-for-fluid-responsive-des