Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

javascript - How can I get the height of the baseline of a certain font?

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.

How can I do this in javascript?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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
=======================

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))

then, smoke it with:

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

--

Give it a try at: http://bl.ocks.org/3157389


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...