Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - How can I measure how many characters will fit the width of the document?

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.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...