我正在尝试使用 JavaScript 逐个字符地显示从数组中获取的文本。我已经设法用数组的一部分做到了。我找不到换行并显示其余部分的方法。
var container = document.getElementById("container");
var notes = [
{scenario: 1, intro: "This is the introduction.", que: "What is the weight of ....?"},
{scenario: 2, intro: "This is the second scen.", que: "What is the second law of ...?"},
{scenario: 3, intro: "This is the third thing.", que: "What is the third law of ...?"},
];
function splTxt(txt) {
// Split string into characters
t = txt.split('');
return t
}
function terminal(cl, i) {
// Create a div element and display message
var div = document.createElement('div');
div.className = cl;
container.appendChild(div);
// Take the first element of the array
// and extract the intro string
var txt = splTxt(notes[0].intro);
var i = 0;
// Display text, character by character
var display = setInterval(function() {
div.textContent += txt[i];
if (i == (txt.length-1)) {
clearInterval(display);
}
i += 1
}, 100);
}
terminal('blueTh', 0);
显示notes[0].intro
之后, 我希望它换行显示 notes[0].que
.
我试过
var txt = splTxt(notes[0].intro + '<br />' + notes[0].que);
但很明显,它只是显示<br />
并在同一行打印两条消息。
最佳答案
你有两个选择:
插入
<br />
并告诉浏览器将其解析为 HTML。您可以使用
innerHTML
来做到这一点属性而不是textContent
.这将允许您使用 HTML 内容,例如
<br />
, 但你必须逃脱&
,<
,>
当它们应该是纯文本时。如果您不信任文本,请不要这样做。var container = document.getElementById("container"); var notes = [ {scenario: 1, intro: "This is the introduction.", que: "What is the weight of ....?"}, {scenario: 2, intro: "This is the second scen.", que: "What is the second law of ...?"}, {scenario: 3, intro: "This is the third thing.", que: "What is the third law of ...?"} ]; function terminal(cl, i) { var div = document.createElement('div'); div.className = cl; container.appendChild(div); var txt = [notes[0].intro, notes[0].que].join('\n').split(''); var i = 0; (function display() { if(i < txt.length) { div.innerHTML += txt[i].replace('\n', '<br />'); ++i; setTimeout(display, 100); } })(); } terminal('blueTh', 0);
<div id="container"></div>
插入换行符并告诉浏览器正确显示它。
在 HTML 中,空白字符默认折叠。您可以通过设置
white-space
来更改此行为CSS 属性为pre
,pre-wrap
或pre-line
.例如,white-space: pre
保留所有空格并且不换行。var container = document.getElementById("container"); var notes = [ {scenario: 1, intro: "This is the introduction.", que: "What is the weight of ....?"}, {scenario: 2, intro: "This is the second scen.", que: "What is the second law of ...?"}, {scenario: 3, intro: "This is the third thing.", que: "What is the third law of ...?"} ]; function terminal(cl, i) { var div = document.createElement('div'); div.className = cl; container.appendChild(div); var txt = [notes[0].intro, notes[0].que].join('\n').split(''); var i = 0; (function display() { if(i < txt.length) { div.textContent += txt[i]; ++i; setTimeout(display, 100); } })(); } terminal('blueTh', 0);
#container { white-space: pre-line; }
<div id="container"></div>
关于JavaScript - 如何逐字符显示文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34370622/