Tweaking performance of elegant solution to text resize for fluid/responsive designs?

∥☆過路亽.° 提交于 2019-12-08 06:22:30

问题


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:

  1. 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.

  2. 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:


  1. See other answer (or put http://jsfiddle.net/cjzEK/1/ on the bottom of your page)

  2. 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:

  1. Creates a function, that is able to set the font size dynamically.
  2. Sets the function as resize event listener.
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!