[英]Wrap text in a javascript variable
我有一個文本變量,我需要包裝文本:
我的代碼:
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();
我怎樣才能換行這個文本? 我用innerHTML
打印i
,但我需要在 html 中包裝像br
這樣的文本。
只需在 css 中使用width
,一切都在開箱即用。
我建議在完成后使用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"/>
在 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>
但是,我確實建議創建一些額外的邏輯,這些邏輯將查找前一個空格並在此處中斷,以免單詞中途中斷。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.