如何设置正文相对于屏幕大小的字体大小

How to set the font-size of the body relative to the screensize

本文关键字:屏幕 字体 相对于 正文 何设置 设置      更新时间:2023-09-26

嗯,我目前正在做一些事情,但现在我正在构建一个移动版本,对于那个移动版本,我想设置相对于窗口的文本大小。我试图这样做:

// Getting the right font-size
var viewportWidth  = document.documentElement.clientWidth;
var viewportHeight = document.documentElement.clientHeight;
document.getElementsByTagName("body")[0].style.fontSize = (viewportHeight / 10);

但出于某种原因,它给了我这个告诉我:

Uncaught TypeError: cannot read 'style' of type undefined.

你们能帮我解决这个问题吗,或者有没有其他方法(可能使用 css)来解决我的问题。

谢谢。

您的错误消息告诉您document.getElementsByTagName("body")[0]会给您undefined。因此,在脚本运行时没有 body 元素(因此无法更改其样式)。

也:

  • 将其移出head
  • 将其转换为函数,可以在读取/加载文档时调用/等

此外,CSS font-size 属性需要长度,长度需要单位。

试试这个:

document.addEventListener('load', function(){
   var viewportWidth  = document.documentElement.clientWidth;
   var viewportHeight = document.documentElement.clientHeight;
   document.body.style.fontSize = (viewportHeight / 10);
}, false);

尝试 document.getElementsByTagName("body")[0].style.fontSize = (viewportHeight/10) + "px";

或您想要使用的任何其他单位。

也看看这里,它可能就是你要找的

http://snook.ca/archives/html_and_css/vm-vh-units

http://dev.opera.com/articles/view/css-viewport-units/