开发者

Calculate how many characters (from a string) will fit into a div without making it wrap?

So I have a <div></div>. I want to know how much (in length) of a string will fit in it before it wraps to the next line. The script should take into account the width of the element (real clientWidth), the left and right margins, and the left and right paddings.

<div id="stackoverflow"></div>

And JavaScript, assuming the magic function is calculate:

calculate("#stackoverflow","the string to be inputed to the div");
// That should开发者_如何学运维 either output how much of the string fits in the div
// or the string's length if it fits without wrapping.

The selector #stackoverflow isn't important, it's just easier to understand.

At this point, my only idea is to have a while loop that adds a character to the div and then checks if the div has wrapped, and if not continue etc then return the character count, but it takes too long!

I honestly don't care if an answer uses jQuery, since I can pretty much translate it to plain JS without any pain.


Your method is good, but can be optimised:

You can render a copy of the div off-screen (and as an immediate child of body) to minimize reflows and repaints.

Also start with an estimate of the number of characters by measuring the width of say 5 characters (the more the better the estimate) and divide the clientWidth by this width. Then you can add/subtract characters from there. If you're doing this for multiple divs of the same width, then cache the previous value as the starting estimate for the next line.


There are too many details out of your knowledge and control that can make anything other than asking the browser mess up. But if you wish to speed it up, the simplest is to do a binary search to figure out where the div wraps. That will be an order of magnitude improvement on the solution that you say is too slow.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜