简体   繁体   English

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

[英]How can i get default font size in pixels by using JavaScript or 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.如您所知,em 是一种相对字体度量,其中一个 em 等于默认字体大小中字母“M”的高度。 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 ?但是如何使用 JavaScript 或 JQuery 获得当前环境的默认字体大小(以像素为单位)?

regards,问候,

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())警报(getDefaultFontSize())

I believe the M-principle is a myth.我相信 M 原则是一个神话。 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.至少http://www.w3.org/TR/CSS21/syndata.html的以下文档证明基于 M 原理的计算过于复杂且不必要。

The 'em' unit is equal to the computed value of the 'font-size' property of the element on which it is used. 'em' 单位等于使用它的元素的 'font-size' 属性的计算值。 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.例外是当 'em' 出现在 'font-size' 属性本身的值中时,在这种情况下,它指的是父元素的字体大小。 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.在没有祖先放大的情况下,1em 正好等于像素字体大小。

  2. Since ancestor magnification with ems and percent works in well defined ways a simple loop will calculate exact font sizes, assuming: no CSS;由于使用 em 和百分比的祖先放大以明确定义的方式工作,因此一个简单的循环将计算精确的字体大小,假设: 没有 CSS; 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.由于 ems 测量宽度,您始终可以通过创建一个 1000 ems 长的 div 并将其 client-Width 属性除以 1000 来计算确切的像素字体大小。我似乎记得 ems 被截断到最近的千分之一,所以您需要 1000 ems避免错误地截断像素结果。

  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.您可能可以创建 M 原则失败的字体,因为 em 基于 font-size 属性而不是实际字体。 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.假设您有一个奇怪的字体,其中 M 是其他字符大小的 1/3,而您的字体大小为 10 像素。 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.我有点认为字体大小是最大字符高度的保证,因此 M 不会是 10 像素,所有其他字符都是 30 像素。

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 window.getComputedStyle(document.body) - 获取 body 的所有样式
  2. getPropertyValue('font-size') - to get a string value of font-size, example: (16px) getPropertyValue('font-size') - 获取字体大小的字符串值,例如: (16px)
  3. match(/\\d+/)[0]) - to get only a number part, example: (16) - string match(/\\d+/)[0]) - 仅获取数字部分,例如: (16) - 字符串
  4. Number(...) - to convert number part into a number, example: (16) - number Number(...) - 将数字部分转换为数字,例如: (16) - 数字

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.我过去见过/使用过的一个技巧是渲染一些文本(比如 50 个任意字符,或 Ms),然后测量渲染容器的大小并进行数学计算以确定单个字符的高度和宽度。 Is this what you're going for?这是你要去的吗? You can do the rendering in the background so the user doesn't see it.您可以在后台进行渲染,这样用户就看不到它了。

Using jQuery (assuming that you want the font size of a specific element):使用 jQuery(假设您想要特定元素的字体大小):

var originalFontSize = $('#your_element_id_here').css('font-size') ; 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:如果您同时使用 Prototype 和 jQuery,您将需要使用 jQuery 前缀而不是美元符号:

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

This will return the value as a string like so: 16px.这会将值作为字符串返回,如下所示:16px。

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. *如果正文在代码中的其他任何地方(可能在某些 css 中)具有不同的 fontSize 声明,则该函数将返回该值。 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.以上将返回 20px 的 fontSize 值。


Fully tested and works for me (chrome 22.0.1229.94 m and firefox 13.01). 经过全面测试并适合我(chrome 22.0.1229.94 m 和 firefox 13.01)。

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.除非你的应用依赖它——让用户处理它。

This works in FF.这适用于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>

如果您使用rem作为单位,则默认的 'font-size' 需要取自<html> ,而不是来自 body 或其他。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM