Work out how many characters can fit into DIV with JavaScript

前端 未结 1 773
春和景丽
春和景丽 2021-01-13 08:10

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.

1条回答
  •  情歌与酒
    2021-01-13 08:32

    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;
       }
    }
    
    
    

    0 讨论(0)
提交回复
热议问题