如何获得某种字体的基线高度? [英] How can I get the height of the baseline of a certain font?

查看:149
本文介绍了如何获得某种字体的基线高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够找到基线的高度 javascript中的div中的一段文本.

I'm hoping to be able to find the height of the baseline of a piece of text in a div using javascript.

我无法使用预定义的字体,因为许多用户将在其浏览器中使用较大的字体设置.

I can't use a predefined font, because many of my users will be using a larger font setting in their browser.

如何在javascript中做到这一点?

How can I do this in javascript?

推荐答案

为此我制作了一个小型jQuery插件.原理很简单:

I made a tiny jQuery plugin for that. The principle is simple:

在一个容器中,插入2个内联元素,它们的内容相同,但是其中一个样式的.非常小,另一个样式的A非常大. 然后,由于默认情况下为vertical-align:baseline,因此基线如下:

In a container, insert 2 inline elements with the same content but one styled very small . and the other very big A. Then, since there are vertical-align:baseline by default, the baseline is given as follow:

       ^ +----+ ^
       | | +-+| | top
height | |.|A|| v
       | | +-+| 
       v +----+

=======================
baseline = top / height
=======================

这是coffeescript中的插件(

Here is the plugin in coffeescript (JS here):

$ = @jQuery ? require 'jQuery'

detectBaseline = (el = 'body') ->
  $container = $('<div style="visibility:hidden;"/>')
  $smallA    = $('<span style="font-size:0;">A</span>')
  $bigA      = $('<span style="font-size:999px;">A</span>')

  $container
    .append($smallA).append($bigA)
    .appendTo(el);
  setTimeout (-> $container.remove()), 10

  $smallA.position().top / $bigA.height()

$.fn.baseline = ->
  detectBaseline(@get(0))

然后,烟熏:

$('body').baseline()
// or whatever selector:
$('#foo').baseline()

-

尝试一下: http://bl.ocks.org/3157389

这篇关于如何获得某种字体的基线高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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