JavaScript 如何根据窗口大小设置字体大小
给定一个HTML文档,任务是使用JavaScript根据窗口大小改变字体大小。
方法1
- 首先使用一个函数将文档元素的字体大小转换为em或%。
- 在窗口大小调整时调用该函数。它会根据窗口大小改变字体大小。
示例: 下面是一个实现了上述方法的示例。
<h1 id="h1" style="color: green">
GeeksForGeeks
</h1>
<p id="GFG_UP" style="font-weight: bold;">
</p>
<script>
var up = document.getElementById('GFG_UP');
var h1 = document.getElementById('h1');
up.innerHTML = "Resize the window to change"
+ "the font-size based on window-size";
h1.setFont = function (font) {
var size = this.offsetWidth,
font_size = size * font;
this.style.fontSize = font_size + '%';
return this
};
h1.setFont(0.50);
window.onresize = function () {
h1.setFont(0.50);
}
</script>
输出:

方法2
使用 vw(视口)单位 将字体大小与视口关联起来转换字体大小。
示例: 此示例实现了视口方法。
<h1 style="color: green; font-size: 5vw;">
GeeksForGeeks
</h1>
<p id="GFG_UP" style="font-weight: bold;">
</p>
<script>
var up = document.getElementById('GFG_UP');
up.innerHTML = "Resize the window to change"
+ "the font-size based on window-size";
</script>
输出:

极客教程