简体   繁体   English

在 javascript 变量中换行文本

[英]Wrap text in a javascript variable

I have a text variable and I need to wrap the text:我有一个文本变量,我需要包装文本:

My code:我的代码:

var text = "Test test test test test test";
                
            function typing(){
                if(i<text.length){
                    document.getElementById("text").innerHTML += text.charAt(i);
                    i++;
                    setTimeout(typing,50);
                }
            }
            typing();

How can I wrap this text?我怎样才能换行这个文本? I print i with an innerHTML , but I need to wrap the text like br in html.我用innerHTML打印i ,但我需要在 html 中包装像br这样的文本。

Just use width in css, everything is working out of the box.只需在 css 中使用width ,一切都在开箱即用。

I recommend to use setInterval() and clearInterval() when it's done.我建议在完成后使用setInterval()clearInterval()

 var text = "Test test test test test test"; var i = 0; function typing(){ if (i<text.length) { document.getElementById("text").innerHTML += text.charAt(i); i++; setTimeout(typing,50); } } typing();
 #text{ width: 5em; }
 <div id="text"/>

Adding the <br> tag after X number of chars:在 X 个字符后添加<br>标签:

 const text = 'Text text text text text text text' const maxchars = 12; let i = 0; function typing(){ if (i < text.length) { const char = text.charAt(i); let addChar = char; // Breaks the text at the max length of chars if ((i % maxchars) === maxchars -1) { addChar += '<br>'; } // Getting the element that has the id text const element = document.getElementById("text") // Adding the char to the element element.innerHTML += addChar; i++; setTimeout(typing,50); } } typing();
 <p id='text'></p>

However I do recommend creating some extra logic that will look up the previous space and break there for not words breaking halfway in.但是,我确实建议创建一些额外的逻辑,这些逻辑将查找前一个空格并在此处中断,以免单词中途中断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM