如何计算跨度中每个字符的宽度和高度 [英] how to calculate width and height of each character in a span

查看:226
本文介绍了如何计算跨度中每个字符的宽度和高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



说的是,html看起来像:

 < span style =font-size:12px>测试100< span> 

所以,一种方法是用span范围的样式为每个角色制作一个虚拟范围,并将其附加到dom并获取它的高度和宽度。



使用查询的示例:

  var x = $('< span style =font-size:12px>'+'T'+'< / span'>); 
$('body')。append(x);
var h = x.height(),w = x.width();
x.remove();

但这是低效的。有没有其他方法可以做到这一点?

解决方案

你不能真正得到一个字符的大小,因为它占用的空间取决于它旁边的字符。



例如,字符 A V 紧接在一起,以便它们比 A旁边的 A 更接近。 或者 V 旁边的 V 。放置相同数量的字符交错,比将它们放在旁边的相同字符占用的空间更少:



AVAVAVAVAVAVAVAVAVAVAVAVAVAVAVAV -
AAAAAAAAAAAAAAAVVVVVVVVVVVVVVV


What is the best way to calculate the width and height of each character in a span.

Say, the html looks like:

 <span style="font-size:12px">Test 100<span>

So, one way is to make a dummy span for each character with the span's style and append it to dom and get it's height and width.

Example, using query:

 var x = $('<span style="font-size:12px">' + 'T' + '</span'>);
 $('body').append(x); 
 var h = x.height(),  w= x.width();
 x.remove();

But this is inefficient. Is there any other way to do it ?

解决方案

You can't really get the size of a character, because the amount of space it takes up depends on which characters it is next to.

For example, the characters A and V next to each other are kerned so that they are closer together than an A next to an A or a V next to a V. Putting the same number of characters interleaved takes less space than putting them next to the same characters:

AVAVAVAVAVAVAVAVAVAVAVAVAVAVAV
AAAAAAAAAAAAAAAVVVVVVVVVVVVVVV

这篇关于如何计算跨度中每个字符的宽度和高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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