如何在HTML中获取字体大小

82
我正在阅读这里的一个问题,试图获取文本的字体大小。他们给出的答案是使用测量方法获取像素大小。我想要做的就是获得字体大小值,以便更改它。
例如:
var x = document.getElementById("foo").style.fontSize;
document.getElementById("foo").style.fontSize = x + 1;

这个例子无法正常工作,但是下面的两个例子可以:
  1. document.getElementById("foo").style.fontSize = "larger";
  2. document.getElementById("foo").style.fontSize = "smaller";
唯一的问题是它只能改变一次字体大小。
9个回答

231

仅仅获取元素的 style.fontSize 可能行不通。如果 font-size 是由样式表定义的,那么这将报告 ""(空字符串)。

你应该使用 window.getComputedStyle

var el = document.getElementById('foo');
var style = window.getComputedStyle(el, null).getPropertyValue('font-size');
var fontSize = parseFloat(style); 
// now you have a proper float for the font size (yes, it can be a float, not just an integer)
el.style.fontSize = (fontSize + 1) + 'px';

2
注意,例如"display"将返回"block",即使父元素可能为“none”,这会使此元素变得不可见。但是像字体大小这样的属性将继承自父元素的值。 - FlorianB
为什么是 fontSize + 1 - vishvAs vAsuki
3
原问题询问如何将字体大小增加1像素。 - Paul Armstrong
太棒了,非常感谢你,伙计。 - Tran Duc Hoa

21
如果您的元素没有font-size属性,您的代码将返回空字符串。并不一定需要您的元素具有font-size属性。该元素可以从父元素继承属性。
在这种情况下,您需要找到计算出的字体大小。尝试这个(不确定IE是否适用)。
var computedFontSize = window.getComputedStyle(document.getElementById("foo")).fontSize;

console.log(computedFontSize);

变量computedFontSize将返回带有单位的字体大小。单位可以是px、em、%。您需要去除单位进行算术运算并分配新值。

6

让它对每个情况都有效

有时(例如使用媒体查询)上述解决方案不起作用,以下是如何在任何情况下实现它:

const fontSize = window.getComputedStyle(el).fontSize

5
如果您正在使用Jquery,则以下是解决方案。
var fontSize = $("#foo").css("fontSize");
fontSize  = parseInt(fontSize) + 1 + "px";
$("#foo").css("fontSize", fontSize );

希望这会有效。


3

这很简单又有帮助!根据需要替换 el

window.getComputedStyle(document.querySelector('el')).fontSize;

更新:

使用像Chrome这样的开发者工具会更好。请参见附图。

在此输入图片描述

在此输入图片描述


2
  1. 如果 HTML 元素内联样式,您可以使用 .style.fontSize 来获取 字体大小
  2. HTML 元素 没有 内联样式 时,您必须使用 Window.getComputedStyle() 函数来获取 字体大小

这是我的演示代码!

function tureFunc() {
    alert(document.getElementById("fp").style.fontSize);
    console.log(`fontSize = ${document.getElementById("fp").style.fontSize}`);
}
function falseFunc() {
    alert( false ? document.getElementById("fh").style.fontSize : "check the consloe!");
    console.log(`fontSize = ${document.getElementById("fh").style.fontSize}`);
}
function getTheStyle(){
    let elem = document.getElementById("elem-container");
    let fontSize = window.getComputedStyle(elem,null).getPropertyValue("font-size");
    // font-size !=== fontSize
    console.log(`fontSize = ${fontSize}`);
    alert(fontSize);
    document.getElementById("output").innerHTML = fontSize;
}
// getTheStyle();
<p id="fp" style="font-size:120%">
    This is a paragraph.
    <mark>inline style : <code>style="font-size:120%"</code></mark>
</p>
<button type="button" onclick="tureFunc()">Return fontSize</button>
<h3 id="fh">
    This is a H3. <mark>browser defualt value</mark>
</h3>
<button type="button" onclick="falseFunc()">Not Return fontSize</button>
<div id="elem-container">
<mark>window.getComputedStyle & .getPropertyValue("font-size");</mark><br/>
<button type="button" onclick="getTheStyle()">Return font-size</button>
</div>
<div id="output"></div>

参考链接:

https://developer.mozilla.org/zh-CN/docs/Web/API/Window/getComputedStyle

该链接介绍了一个名为getComputedStyle的方法,可以获取指定元素的计算样式。这个方法在IT技术中非常常见,特别是在Web开发中。

2

从fontSize获取的值类似于“12px”或“1.5em”,因此将其加1会导致“12px1”或“1.5em1”的结果。您可以使用以下方法获取并处理字体大小:

var fontSize = parseInt(x);
fontSize = fontSize + 1 + "px";
document.getElementById("foo").style.fontSize = fontSize;

很遗憾,那并没有起作用,但是感谢您告诉我返回值中添加了“px”和“em”。 - Mark Walsh
parseInt(string value) 做到了这一点。它基本上修剪了值中的字符串部分,例如 pxem 等。有了这个,如果您知道只会使用某个单位来表示大小,则不需要进行太多的操作。 - Puspam

0

以下是获取顶层font-size(与html标签相关联)的方法:

window.getComputedStyle(document.getElementsByTagName('html')[0]).getPropertyValue('font-size');

检查是否为默认的16像素很有用。


0

试试这个,它肯定会帮助你确定字体大小

var elem = document.createElement('div');
var t=document.createTextNode('M')
elem.appendChild(t);
document.body.appendChild(elem);

var myfontSize = getStyle(elem,"fontSize")
alert(myfontSize)
document.body.removeChild(elem);

function getStyle(elem,prop){
if (elem.currentStyle) {
var res= elem.currentStyle.margin;
} else if (window.getComputedStyle) {
if (window.getComputedStyle.getPropertyValue){
var res= window.getComputedStyle(elem, null).getPropertyValue(prop)}
else{var res =window.getComputedStyle(elem)[prop] };
}
return res;
}

我们可以进一步使用getter和setter来确定字体大小是否被任何代码后续更改。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接