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

隐身守侯 提交于 2019-12-06 02:51:47

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.

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