计算多少个字符(来自一个字符串)将适合div而不进行包装? [英] Calculate how many characters (from a string) will fit into a div without making it wrap?

查看:80
本文介绍了计算多少个字符(来自一个字符串)将适合div而不进行包装?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有< div>< / div> 。我想知道在它换行到下一行之前,字符串中有多少(长度)。该脚本应考虑元素的宽度(实际 clientWidth ),左右边距以及左右填充。

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>

和JavaScript,假设魔术函数是计算

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.

选择器 #stoveroverflow 并不重要,它更容易理解。

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

此时,我唯一的想法是在循环时添加 div中的一个字符,然后检查div是否已经包装,如果没有继续等,则返回字符数,但这需要太长时间!

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!

老实说我不知道关心一个答案是否使用jQuery,因为我几乎可以毫不费力地将它翻译成普通的JS。

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:

您可以在屏幕外渲染div的副本(并作为身体的直接子项)以最大限度地减少回流和重绘。

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

同样从估计的数量开始通过测量5个字符的宽度(估计越好)并将clientWidth除以此宽度来确定字符数。然后你可以从那里添加/减去字符。如果您对相同宽度的多个div执行此操作,则将先前的值缓存为下一行的起始估计值。

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而不进行包装?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆