Javascript 在最大字符数的行中剪切字符串
我有一个字符串“Lorem ipsum door sit amet,concertetur adipising elit,sed do eiusmod temporal incidedut ut laboure and dolore magna aliqua” 我有一个容器,里面装着这个句子。我的容器有宽度,文本有字体大小 我想把我的句子分成几行,不删减单词 检查我的代码:Javascript 在最大字符数的行中剪切字符串,javascript,html,Javascript,Html,我有一个字符串“Lorem ipsum door sit amet,concertetur adipising elit,sed do eiusmod temporal incidedut ut laboure and dolore magna aliqua” 我有一个容器,里面装着这个句子。我的容器有宽度,文本有字体大小 我想把我的句子分成几行,不删减单词 检查我的代码: var containerWidth = 200; var el = document.getElemen
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;
}
}
然而,正如你所看到的,当它出现在else中时,单词不会出现在下一行中,我知道这是为什么,因为它没有添加到txt+=wordsTab[I]+''
和i直接递增(在本例中,它取i=4的值,因此i=3被忽略)
我想要的是,当它进入else时,我们应用I-1(不知道这是否是好方法)
谢谢你我想你想要的是
txt=wordsTab[I]+''代码>而不是txt=“”
.I在else中输入txt=“”,以重置新行的值,但您希望在其中输入单词,否则将被忘记。请注意,我使用的是=
而不是+=
。您在这里想要实现什么?好的@AndrewMorton您是对的!你能查一下这个吗?为什么最后一个字没有出现?非常感谢。
// In this case :
wordsTab[0] = "lorem"; wordsTab[1] = "ipsum"; wordsTab[3] = "dolor"