根据(根元素的)当前大小增加 javascript 中根元素的字体大小

问题描述 投票:0回答:3

我使用 rem 单位在 CSS 中定义字体大小,我想使用 javascript 向最终用户提供更改字体大小的选项。

我可以使用预定义的字体大小并使用以下函数更改字体大小:

document.documentElement.style.fontSize = "67.5%"

我想要做的是将字体大小更改为当前字体大小的一个因素。基本上是这样的:

document.documentElement.style.fontSize = Number(document.documentElement.style.fontSize) + Number(5) + "%"

我该如何实现这一目标?

玩耍的小提琴:http://jsfiddle.net/rahulthewall/wX94C/1/

javascript html css fonts
3个回答
7
投票

纯 JavaScript 会是这样的

var root = document.querySelector(":root");

root.style.fontSize = "25px";

更新:使用 window.getCompulatedStyle

    var root = document.querySelector("p"),
       style = window.getComputedStyle(root, null).getPropertyValue('font-size'),
    fontSize = parseFloat(style);

root.style.fontSize = (10*fontSize)+'px';

演示


2
投票

鉴于 rem 单位基于您案例中

font-size
元素的
<html>
,您应该能够更改该
font-size
并观察其余字体大小的变化。

我能够使用此代码:

jQuery(document).ready(function() { jQuery('html').css('font-size', '24px'); });

24px
可以更换为任何尺寸。)


0
投票

对于纯 JavaScript 实现:

document.querySelector("html").style.fontSize = `calc(1rem * 1.05%)`
© www.soinside.com 2019 - 2024. All rights reserved.