开发者

Work out how many characters can fit into DIV with JavaScript

开发者 https://www.devze.com 2023-01-09 23:11 出处:网络
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?

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

精彩评论

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

关注公众号