计算一个 div 可以容纳多少个字符(来自字符串)而不使其换行?
所以我有一个 。我想知道在换行到下一行之前,字符串可以容纳多少(长度)。脚本应考虑元素的宽度(真实的
clientWidth
)、左右边距以及左右内边距。
<div id="stackoverflow"></div>
对于 JavaScript,假设神奇的函数是 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.
选择器 #stackoverflow
并不重要,它只是更容易理解。
此时,我唯一的想法是有一个 while
循环,向 div 添加一个字符,然后检查 div 是否已换行,如果没有继续等,则返回字符计数,但这需要太长了!
老实说,我不在乎答案是否使用 jQuery,因为我几乎可以将其转换为纯 JS,没有任何痛苦。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的方法很好,但可以优化:
您可以在屏幕外渲染 div 的副本(并作为 body 的直接子级),以最大程度地减少回流和重绘。
还可以通过测量 5 个字符的宽度(估计越多越好)来估计字符数,然后将 clientWidth 除以该宽度。然后您可以从那里添加/减去字符。如果您对相同宽度的多个 div 执行此操作,则将先前的值缓存为下一行的起始估计值。
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.
有太多的细节超出了你的知识和控制范围,除了询问浏览器之外,这些细节可能会让其他事情变得混乱。但如果您希望加快速度,最简单的方法是进行二分搜索来找出 div 换行的位置。这将是您所说的太慢的解决方案的一个数量级的改进。
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.