[英]How can I get the height of the baseline of a certain font?
我为此制作了一个小小的jQuery插件。 原理很简单:
在容器中,插入2个具有相同内容的内联元素,但其中一个样式非常小.
而另一个非常大的A
然后,由于默认情况下有vertical-align:baseline
,因此基线如下:
^ +----+ ^
| | +-+| | top
height | |.|A|| v
| | +-+|
v +----+
=======================
baseline = top / height
=======================
这是coffeescript中的插件(这里是JS ):
$ = @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
继Alan Stearns( http://blogs.adobe.com/webplatform/2014/08/13/one-weird-trick-to-baseline-align-text/ )发现内联块元素改变了基线对齐后其他内联元素,我整理了一个演示,我发现它比https://stackoverflow.com/a/11615439/67190更准确,实际上更简单的JavaScript派生价值: http : //codepen.io/georgecrawford/ pen / gbaJWJ 。 希望它有用。
<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;
}
Vanilla JS,在Chrome,Firefox和Edge上无需测试任何字体信息 :
function getBaselineHeight(el){ let bottomY = el.getBoundingClientRect().bottom;//viewport pos of bottom of el let baselineLocator = document.createElement("img"); // needs to be an inline element without a baseline (so its bottom (not baseline) is used for alignment) el.appendChild(baselineLocator); baselineLocator.style.verticalAlign = 'baseline' ; // aligns bottom of baselineLocator with baseline of el let baseLineY = baselineLocator.getBoundingClientRect().bottom;//viewport pos of baseline el.removeChild(baselineLocator); return (bottomY - baseLineY) ; } function positionLine(){ let line = document.getElementById("line"); let lorem = document.getElementById("lorem"); let baselineHeight = getBaselineHeight(lorem); let newLinePos = lorem.getBoundingClientRect().bottom - baselineHeight ; line.style.top = newLinePos + "px" ; }
#lorem{ background-color: lightblue; } #line{ position:absolute; left : 0 ; height:1px; width:100% }
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/> <span id="lorem">Lorem ipsum dolor sit amet, consectetur adipiscing elit..</span> <br><br> <button class="btn btn-primary" onclick="positionLine();">position line on baseline</button> <br><br> <svg id="line"> <line x1="0" y1="0" x2="100%" y2="0" style="stroke:rgb(255,0,0);stroke-width:1"></line> </svg>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.