如何使用 JavaScript 或 JQuery 获取默认字体大小(以像素为单位)?

发布于 2024-08-05 13:06:57 字数 141 浏览 4 评论 0原文

如您所知,em 是一种相对字体测量值,其中 1 em 等于默认字体大小中字母“M”的高度。使用它的一个优点是您可以调整文本大小。

但是如何使用 JavaScript 或 JQuery 获取当前环境的默认字体大小(以像素为单位)?

问候,

As you know em is a relative font measurement where one em is equal to the height of the letter "M" in the default font size. An advantage in using it is because you will be able to resize the text.

But how can i get default font size of current environment (in pixels) by using JavaScript or JQuery ?

regards,

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

乙白 2024-08-12 13:06:57

在某些情况下这可能很有用 -

function getDefaultFontSize(pa){
 pa= pa || document.body;
 var who= document.createElement('div');

 who.style.cssText='display:inline-block; padding:0; line-height:1; position:absolute; visibility:hidden; font-size:1em';

 who.appendChild(document.createTextNode('M'));
 pa.appendChild(who);
 var fs= [who.offsetWidth, who.offsetHeight];
 pa.removeChild(who);
 return fs;
}

alert(getDefaultFontSize())

There are a couple of situations this can be useful-

function getDefaultFontSize(pa){
 pa= pa || document.body;
 var who= document.createElement('div');

 who.style.cssText='display:inline-block; padding:0; line-height:1; position:absolute; visibility:hidden; font-size:1em';

 who.appendChild(document.createTextNode('M'));
 pa.appendChild(who);
 var fs= [who.offsetWidth, who.offsetHeight];
 pa.removeChild(who);
 return fs;
}

alert(getDefaultFontSize())

你げ笑在眉眼 2024-08-12 13:06:57

可以使用以下代码行来完成:

const fontSize = Number(window.getComputedStyle(document.body).getPropertyValue('font-size').match(/\d+/)[0])
  1. window.getComputedStyle(document.body) - 获取 body 的所有样式
  2. getPropertyValue('font-size') - 到获取字体大小的字符串值,例如:(16px)
  3. match(/\d+/)[0]) - 仅获取数字部分,例如:< em>(16) - 字符串
  4. Number(...) - 将数字部分转换为数字,例如:(16) - 数字

It can be done using this line of code:

const fontSize = Number(window.getComputedStyle(document.body).getPropertyValue('font-size').match(/\d+/)[0])
  1. window.getComputedStyle(document.body) - to get all the styles for body
  2. getPropertyValue('font-size') - to get a string value of font-size, example: (16px)
  3. match(/\d+/)[0]) - to get only a number part, example: (16) - string
  4. Number(...) - to convert number part into a number, example: (16) - number
偏闹i 2024-08-12 13:06:57

我相信 M 原则是一个神话。至少来自 http://www.w3.org/TR/CSS21 的以下文档/syndata.html证明基于M原理的计算过于复杂且不必要。

“em”单位等于计算的
'font-size' 属性的值
使用它的元素。这
例外是当“em”出现在
“font-size”属性的值
本身,在这种情况下它指的是
父元素的字体大小。它
可用于垂直或水平
测量。 (这个单位也是
有时称为四边形宽度
印刷文本。)

根据本文档,以下内容正确。

  1. 没有祖先放大率,1em 正好等于像素字体大小。

    没有

  2. 由于使用ems和百分比的祖先放大以明确定义的方式工作,一个简单的循环将计算精确的字体大小,假设:没有CSS;并且某些祖先将其字体大小设置为绝对单位。

  3. 由于ems测量宽度,你总是可以通过创建一个1000ems长的div并将其client-Width属性除以1000来计算精确的像素字体大小。我似乎记得ems被截断到最接近的千分之一,所以你需要1000 ems 以避免像素结果的错误截断。

  4. 您可能可以创建一种 M 原则失败的字体,因为 em 是基于字体大小属性而不是实际字体。假设您有一种奇怪的字体,其中 M 是其他字符大小的 1/3,并且您的字体大小为 10 像素。我认为字体大小是最大字符高度的保证,因此 M 不会是 10 像素,所有其他字符不会是 30 像素。

I believe the M-principle is a myth. At the very least the following documentation from http://www.w3.org/TR/CSS21/syndata.html proves that calculations based on the M-principle are overly complicated and unnecessary.

The 'em' unit is equal to the computed
value of the 'font-size' property of
the element on which it is used. The
exception is when 'em' occurs in the
value of the 'font-size' property
itself, in which case it refers to the
font size of the parent element. It
may be used for vertical or horizontal
measurement. (This unit is also
sometimes called the quad-width in
typographic texts.)

From this documentation the following are true.

  1. Without ancestor magnification, 1em is exactly equal to the pixel font size.

  2. Since ancestor magnification with ems and percent works in well defined ways a simple loop will calculate exact font sizes, assuming: no C.S.S; and some ancestor has it's font size set in absolute units.

  3. Since ems measure width you can always compute the exact pixel font size by creating a div that is 1000 ems long and dividing its client-Width property by 1000. I seem to recall ems are truncated to the nearest thousandth, so you need 1000 ems to avoid an erroneous truncation of the pixel result.

  4. You probably can create a font where the M-principle fails since em is based on the font-size attribute not on the actual font. Suppose you have a weird font where M is 1/3 the size of the other characters and you have a font size of 10 pixels. I kind of think the font-size is a guarantee of maximal character height and so the M will not be 10 pixels and all other characters 30 pixels.

泛滥成性 2024-08-12 13:06:57

如果您使用 rem 作为单位,则默认的“font-size”需要从 获取,而不是从 body 或其他。

alert(window.getComputedStyle(document.documentElement).getPropertyValue('font-size'))

If you use rem as unit the default 'font-size' need take from <html>, not from body or other.

alert(window.getComputedStyle(document.documentElement).getPropertyValue('font-size'))

老街孤人 2024-08-12 13:06:57

我过去见过/使用过的一个技巧是渲染一些文本(例如 50 个任意字符,或 Ms),然后测量渲染容器的大小并进行数学计算以计算出单个字符的高度和宽度。这就是你想要的吗?您可以在后台进行渲染,这样用户就看不到它。

One trick I've seen/used in the past is to render some text (say 50 arbitrary characters, or Ms) and then measure the size of the rendered container and do the math to figure out the height and width of a single character. Is this what you're going for? You can do the rendering in the background so the user doesn't see it.

她比我温柔 2024-08-12 13:06:57

使用 jQuery(假设您需要特定元素的字体大小):

var originalFontSize = $('#your_element_id_here').css('font-size');

如果您使用 Prototype 以及 jQuery,则需要使用 jQuery 前缀而不是美元符号:

var originalFontSize = jQuery('#your_element_id_here').css('font-size');

这将以字符串形式返回值,如下所示:16px。

Using jQuery (assuming that you want the font size of a specific element):

var originalFontSize = $('#your_element_id_here').css('font-size');

If you're using Prototype as well as jQuery, you'll want to use the jQuery prefix instead of the dollar sign:

var originalFontSize = jQuery('#your_element_id_here').css('font-size');

This will return the value as a string like so: 16px.

孤檠 2024-08-12 13:06:57

尽管获取默认字体大小似乎是一个好主意 - 如果要设置页面布局等,那么让用户处理它可能是更安全的做法。

如果他们的字体较大,那是因为他们是盲人,反之亦然。我建议设置默认值并“推荐”分辨率/尺寸。除非你的应用程序依赖它——让用户处理它。

Although it seems like getting the default font size might be a good idea -- if it's to set the layout of your pages and such, it's probably a safer practice to just let the user handle that.

If they have their font size larger - it's because they're blind and vice versa. I'd recommend setting your defaults and 'recommending' a resolution/size. Unless your app depends on it -- let the user handle it.

笑红尘 2024-08-12 13:06:57

这在 FF 中有效。

<script>
function getStyle(el,styleProp)
{
    var x = document.getElementById(el);
    if (x.currentStyle)
        var y = x.currentStyle[styleProp];
    else if (window.getComputedStyle)
        var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
    return y;
}

function GetSt()
{
    var font_size = getStyle("div2","fontSize"); 
    alert ( font_size );
}

</script>
<div id="div1" style="height: 100px;font-size: 20px;">
<div id="div2" style="font-size: 2em;">
test
</div>
</div>
<button onclick="GetSt();">Click</button>

This works in FF.

<script>
function getStyle(el,styleProp)
{
    var x = document.getElementById(el);
    if (x.currentStyle)
        var y = x.currentStyle[styleProp];
    else if (window.getComputedStyle)
        var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
    return y;
}

function GetSt()
{
    var font_size = getStyle("div2","fontSize"); 
    alert ( font_size );
}

</script>
<div id="div1" style="height: 100px;font-size: 20px;">
<div id="div2" style="font-size: 2em;">
test
</div>
</div>
<button onclick="GetSt();">Click</button>
夜灵血窟げ 2024-08-12 13:06:57

我认为这就是您正在寻找的:

function getDefaultFontSize () {
// this will return the default* value assigned to the style: fontSize
defsize=(document.body.style.fontSize)
alert('The default font size of your browser is: "' + defsize + '"');
}

*如果 body 在代码中的其他任何地方(也许在某些 css 中)有不同的 fontSize 减法,则该函数将返回该值。例如:

<style>body{font-size:20px;}</style>
<script>function getDefaultFontSize () {
defsize=(document.body.style.fontSize)
} </script>

上面将返回 20px 的 fontSize 值。


Fully tested and works for me (chrome 22.0.1229.94 m and firefox 13.01).

I think this is what you're looking for:

function getDefaultFontSize () {
// this will return the default* value assigned to the style: fontSize
defsize=(document.body.style.fontSize)
alert('The default font size of your browser is: "' + defsize + '"');
}

*If body has a different fontSize decleration anywhere else in the code (perhaps in some css) the function will return that value. For example:

<style>body{font-size:20px;}</style>
<script>function getDefaultFontSize () {
defsize=(document.body.style.fontSize)
} </script>

The above will return a fontSize value of 20px.


Fully tested and works for me (chrome 22.0.1229.94 m and firefox 13.01).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文