最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin4浏览0评论

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.

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.

Share Improve this question edited Dec 2, 2011 at 14:17 Andy E 345k86 gold badges480 silver badges450 bronze badges asked May 17, 2009 at 18:39 alvataralvatar 3,3808 gold badges39 silver badges50 bronze badges 1
  • What are you trying to acplish here? There may be a better way. HTML's flow-layout really isn't designed for this sort of thing. – i_am_jorf Commented May 17, 2009 at 18:44
Add a ment  | 

3 Answers 3

Reset to default 6

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.

There is no easy way to do this in HTML.

However, if you really must know, you can probably figure it out with some really ugly javascript:

First, create a <div> with the width you need, put some characters in and request its .height() in pixels. Then, keep adding characters to it and keep checking the .height(), when the height of the <div> changes you know it has grown to fit a new line of text.

You can get the total width available for the browser with

window.innerWidth

And then you can get the width of an element with the following method.

document.getElementById('elem').clientWidth  
发布评论

评论列表(0)

  1. 暂无评论