开发者

Work out how many characters can fit into DIV with JavaScript

Does开发者_开发技巧 anyone know what the best method would be to work out how many characters can fit inside a DIV block in HTML using JavaScript?

Any advise would greatly help.


You could iteratively add your characters to a hidden div and check the width of that. Not sure if there is a better way.

Edit: Something like this:

var targetWidth = document.getElementById('DivToCheck').clientWidth;
var stringToFit = 'abcdefghijk';
var numChars = 0;
for(var i=0; i < stringToFit.length; i++)
{
   document.getElementById('hiddenDiv').innerHTML += stringToFit.charAt(i);
   if (document.getElementById('hiddenDiv').clientWidth > targetWidth)
   {
       numChars = i - 1;
       break;
   }
}

<div id="hiddenDiv" style="visibility: hidden; width: auto;"></div>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜