How can I get the height of the baseline of a cert

2019-01-22 10:05发布

问题:

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?

回答1:

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



回答2:

Following the discovery by Alan Stearns (http://blogs.adobe.com/webplatform/2014/08/13/one-weird-trick-to-baseline-align-text/) that inline-block elements change the baseline alignment of other inline elements, I put together a demo which I found more accurate than https://stackoverflow.com/a/11615439/67190, and actually more simple to derive a value in JavaScript: http://codepen.io/georgecrawford/pen/gbaJWJ. Hope it's useful.

<div>
  <span class="letter">T</span>
  <span class="strut"></span>
<div>
div {
  width: 100px;
  height: 100px;
  border: thin black solid;
}
.letter {
  font-size: 100px;
  line-height: 0px;
  background-color: #9BBCE3;
}
.strut {
  display: inline-block;
  height: 100px;
}