如何获取HTML中的字体大小 [英] How To Get Font Size in HTML

查看:979
本文介绍了如何获取HTML中的字体大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里读取一个问题,试图获取文本的字体大小。他们给出的答案是使用measure方法获取像素大小。所有我想要能够做的是获取字体大小的值,所以我可以改变它。

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.

例如:

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


$ b b

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

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

推荐答案

一个元素的style.fontSize 可能不工作。如果 font-size 由样式表定义,则会报告(空字符串)。

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

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

这篇关于如何获取HTML中的字体大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆