专门为页面上的所有数字设置字体

2022-01-17 00:00:00 regex numbers javascript css font-family

对于我的网页,我选择了一种适用于所有字母的字体.但是,对于所有数字,我想使用不同的字体.

For my webpage, I chose a font that works well for all the letters. However, for all numbers I'd like to use a different font.

有没有办法可以设置 CSS 规则来定位页面上的所有数字?

Is there a way that I can set a CSS rule to target all the numbers on the page?

如果我不能严格使用 CSS,我的第一个想法是使用正则表达式将所有数字与数字"类的范围包围起来,并为该类应用字体.有没有更好的方法来做到这一点?

If I can't do it strictly with CSS, my first thought is to use regular expressions to surround all numbers with a span with a "numbers" class and apply a font for that class. Is there a better way to do this?

推荐答案

您可以在 JavaScript 中相对简单地通过遍历文档来实现,以便将任何数字序列包装在 span 元素中class 属性并在 CSS 中为其声明 font-family.

You can do it in JavaScript relatively simply by traversing the document so that you wrap any sequence of digits in a span element with a class attribute and declare font-family for it in CSS.

原则上在纯 CSS 中也是可能的,尽管目前只有 WebKit 浏览器支持:

It’s possible in principle in pure CSS, too, though only WebKit browsers currently support this:

@font-face {
  font-family: myArial;
  src: local("Courier New");
  unicode-range: U+30-39;
}
@font-face {
  font-family: myArial;
  src: local("Arial");
  unicode-range: U+0-2f, U+40-10FFFF;
}
body { font-family: myArial; }

最后,也是最重要的,不要这样做.如果您对字体中的数字不满意,请不要使用该字体.

Finally, and most importantly, don’t do it. If you are dissatisfied with digits in a font, don’t use that font.

相关文章