如何测量符合文档宽度的字符数? [英] How can I measure how many characters will fit the width of the document?

查看:127
本文介绍了如何测量符合文档宽度的字符数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在JavaScript中编写(我使用的是jQuery),这是一个能够识别适合浏览器窗口一行的字符数的函数。我正在使用等宽字体来缓解这个问题,但如果我将它推广到不同的字体会更好。

I need to write, in JavaScript (I am using jQuery), a function that is aware of the number of characters that fit in a line of the browser window. I'm using a monospace font to ease the problem, but it would be better if I generalize it for different fonts.

我怎么知道会填充多少个字符?在浏览器中排?目的是计算填充一行的字符数。

How can I know how many characters would fill a row in the browser? The intention is to count the number of characters that fill a line.

推荐答案

您可以创建元素并为其添加字符,直到您检测包裹,例如通过观察 offsetHeight 中的变化(你可以使用二分算法对其进行优化)。

You can create element and append characters to it until you detect wrapping, e.g. by observing changes in offsetHeight (you can optimze it using bisection algorithm).

这当然非常依赖于浏览器,系统,已安装的字体和用户的设置,因此每次显示页面,调整大小或用户更改字体大小时,您都必须为每个文本片段计算它(即使是整页缩放也会引入一些可能导致的错误导致字符数改变。)

This is of course very dependent on browser, system, installed fonts and user's settings so you would have to calculate it for each fragment of text each time page is displayed, resized or when user changes font size (even full-page zoom introduces some off-by-one errors which could cause number of characters change).

因此在大多数情况下它可能是一种矫枉过正,如果实施不当会导致比它解决的更多麻烦。

Therefore it may be an overkill in most situations and when implemented poorly cause more trouble than it solves.

还有其他解决方案,例如如果你想确保只有一行可见,你可以使用 white-space:nowrap overflow:hidden 和在某些浏览器中 text-overflow:省略号可以很好地剪切文本。或者,如果您不想剪切单词,请使用带有 overflow的1行高容器:hidden

There are other solutions, e.g. if you want to ensure that only one line is visible you can use white-space:nowrap and overflow:hidden and in some browsers text-overflow:ellipsis to make text cut nicely. Or if you don't want words cut, use 1-line high container with overflow:hidden.

这篇关于如何测量符合文档宽度的字符数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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