如何在 HTML 中获取字体大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15195209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 06:05:49  来源:igfitidea点击:

How To Get Font Size in HTML

javascripthtmlcssfont-size

提问by Mark Walsh

I was reading a question on here trying to get the font size of a text. The answer they gave was to get the pixel size using a measure method. All i want to be able to do is get the font size value so i can change it.

我正在阅读这里的一个问题,试图获取文本的字体大小。他们给出的答案是使用测量方法获得像素大小。我想要做的就是获取字体大小值,以便我可以更改它。

For example:

例如:

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

This example does not work though these two do

尽管这两个可以,但此示例不起作用

  1. document.getElementById("foo").style.fontSize = "larger";
  2. document.getElementById("foo").style.fontSize = "smaller";
  1. document.getElementById("foo").style.fontSize = "larger";
  2. document.getElementById("foo").style.fontSize = "smaller";

The only problem is that it only changes the size once.

唯一的问题是它只更改一次大小。

回答by Paul Armstrong

Just grabbing the style.fontSizeof an element may not work. If the font-sizeis defined by a stylesheet, this will report ""(empty string).

仅抓取style.fontSize元素的 可能不起作用。如果font-size由样式表定义,则将报告""(空字符串)。

You should use window.getComputedStyle.

您应该使用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';

回答by kiranvj

If your element don't have font-size property your code will return empty string. Its not necessary that your element should have font-size property. The element can inherit the properties from parent elements.

如果您的元素没有 font-size 属性,您的代码将返回空字符串。您的元素不必具有 font-size 属性。元素可以继承父元素的属性。

In this case you need to find the computed font-size. Try this (not sure about IE)

在这种情况下,您需要找到计算出的字体大小。试试这个(不确定IE)

var computedFontSize = window.getComputedStyle(document.getElementById("foo")).fontSize;

console.log(computedFontSize);

The variable computedFontSize will return with the font size with unit. Unit can be px, em, %. You need to strip out the unit to do an arithmetic operation and assign the new value.

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

回答by MattDiamant

The value that you are getting from fontSize is something like "12px" or "1.5em", so adding 1 to that string will result in "12px1" or "1.5em1". You can take the font size and manipulate it with:

您从 fontSize 获得的值类似于“12px”或“1.5em”,因此向该字符串添加 1 将导致“12px1”或“1.5em1”。您可以使用字体大小并使用以下方法对其进行操作:

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

回答by Umair Saleem

If you are using Jquery than following is the solution.

如果您使用的是 Jquery,那么以下是解决方案。

var fontSize = $("#foo").css("fontSize");
fontSize  = parseInt(fontSize) + 1 + "px";
$("#foo").css("fontSize", fontSize );

Hope this will work.

希望这会奏效。

回答by Gaurav

Try this it would definately help you in determining the font size

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

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;
}

we can further use getter and setter to determine if fontsize is changed afterwards by any peice of code

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

回答by xgqfrms

  1. if the html elementhas inline style, you can using the .style.fontSizeto get the font-size!
  2. when the html elementdoesn't has inline style, you have to using the Window.getComputedStyle()function to get the font-size!
  1. 如果html 元素具有内联样式,则可以使用.style.fontSize来获取字体大小
  2. html 元素没有内联样式时,您必须使用该Window.getComputedStyle()函数来获取字体大小

here is my demo codes!

这是我的演示代码!

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>

reference links:

参考链接:

https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle

https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle

回答by Alexandre Daubricourt

Making it work for every case

使其适用于每种情况

Sometimes (when using media queries for instance) the above answers don't work, here is how to achieve it anyway:

有时(例如使用媒体查询时)上述答案不起作用,以下是实现它的方法:

const fontSize = window.getComputedStyle(el).fontSize