简体   繁体   中英

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.

Just use width in css, everything is working out of the box.

I recommend to use setInterval() and clearInterval() when it's done.

 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:

 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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