用最大字符数

时间:2017-01-12 12:28:06

标签: javascript html

我有一个字符串" Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua"

我有一个包含这句话的容器。我的容器有宽度,文本有字体大小。

我想把我的句子分成几行而不用切词。

检查我的代码:

    var containerWidth = 200;
    var el = document.getElementById('content'); //get the sentence
    var style = window.getComputedStyle(el, null).getPropertyValue('font-size');  // get the font-size
    var fontSize = parseInt(style); 
    var charPerLine = limit = Math.floor(containerWidth / fontSize); // get the maximum number of characters per line

    el.parentNode.removeChild(el); //remove the sentence

    var wordsTab = el.innerHTML.split(' '); //split each words into an array
    var txt = "";

    for(var i = 0; i < wordsTab.length; i++){          
        if(charPerLine - wordsTab[i].length >= 0){ 
            txt += wordsTab[i] + ' '; // add the word to a string
            charPerLine -= wordsTab[i].length;  // Here I substract the word length to the number max per line
        }

        else{ //Here I create a new div (new line) with the text inside
            var line = document.createElement('div');
            line.innerHTML = txt;
            document.getElementsByTagName('body')[0].appendChild(line);
            //Reset values for the new line
            txt="";
            charPerLine = limit;
        }   
    }

检查出来:https://jsfiddle.net/5omg4078/1/

在这个例子中,我的容器宽度是200px,字体大小是15px,所以字符数最多= 200/15 = 13.我可以放13个字符。 &#34;的Lorem&#34; &安培; &#34; ipsum的&#34;数10个字符。 &#34;悲&#34;使用&#34; lorem ipsum&#34;计算5个字符。它高于13 - >它进入了其他并创建了一条新线。

// In this case : 
wordsTab[0] = "lorem"; wordsTab[1] = "ipsum"; wordsTab[3] = "dolor"

然而,正如你所看到的那样,当它进入else时,单词不出现在下一行中,我知道为什么它是因为它没有被添加到txt += wordsTab[i] + ' ';并且i直接递增(在这个例子它取i = 4的值,所以忘记了i = 3。

我想要的是当它进入其他地方时,我们应用i-1(不知道这是不是好方法)。

谢谢

0 个答案:

没有答案