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

回眸只為那壹抹淺笑 提交于 2019-12-10 10:08:24

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/4929107/calculate-how-many-characters-from-a-string-will-fit-into-a-div-without-making

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!