2016-05-16 69 views
1

你好我不知道我的標題是否有幫助,但這裏是我的問題我想在JS,CSS,HTML中做一個類型編寫器效果,除了當我嘗試添加一條不顯示的新行時,添加一行新文本。如何在腳本中添加新行

\t var str = "<p>I want to put text here then another line under this one</p>", 
 
\t <!--var str = "<p>text here</p>",--> <!--This is what I tried to do to add a new line--> 
 
    i = 0, 
 
    isTag, 
 
    text; 
 

 
(function type() { 
 
    text = str.slice(0, ++i); 
 
    if (text === str) return; 
 
    
 
    document.getElementById('typewriter').innerHTML = text; 
 

 
    var char = text.slice(-1); 
 
    if(char === '<') isTag = true; 
 
    if(char === '>') isTag = false; 
 

 
    if (isTag) return type(); 
 
    setTimeout(type, 80); 
 
}());
#typewriter { 
 
\t \t color: lime; 
 
\t \t text-align: center; 
 
\t }
<div id="typewriter"></div>

+0

你可以用'\ N'或''

回答

0

使用<br />

var str = "<p>I want to put text here<br /> then another line under this one</p>"; 
1

var str = "My text\nSome more text"; 
 
var stra = str.split(""); 
 
var tw = document.getElementById("output"); 
 
function type(){ 
 
    var char = stra.shift(); 
 
    if (char){ 
 
     tw.innerHTML += char; 
 
     setTimeout(type, 80); 
 
    } 
 
    
 
} 
 
type();
<pre id="output"></pre>

0

另一種可能性是使用組段落元件0並將span的顯示樣式屬性添加到block。

window.onload = function() { 
 
    var str = "<p><span>I want to put text here then another line under this one</span><span>text here</span></p>"; 
 

 
    (function type(isInTagArg, indexArg) { 
 
    var index = indexArg || 0; 
 
    if (index >= str.length) 
 
     return; 
 

 
    var isInTag = isInTagArg || false; 
 
    if (isInTag == false) { 
 
     if (str.charAt(index) == '<') { 
 
     return type(true, index + 1); 
 
     } else { 
 
     document.getElementById('typewriter').innerHTML = str.substr(0, index + 1); 
 
     } 
 
    } else { 
 
     if (str.charAt(index) == '>') { 
 
     return type(false, index + 1); 
 
     } 
 
     return type(true, index + 1); 
 
    } 
 
    setTimeout(function() {type(false, index + 1)}, 80); 
 
    }()); 
 
}
#typewriter { 
 
    color: lime; 
 
    text-align: center; 
 
} 
 
#typewriter span 
 
{ 
 
    display: block; 
 
}
<div id="typewriter"></div>

相關問題