空格被 InnerText 属性忽略
我正在尝试编写一个函数(在 JavaScript 中),它会通过一个一个地写下它的字母,每个字母之间有 300 毫秒的停顿,在 <p>
标签中写一个句子,例如例如.我写了以下内容:
I'm trying to write a function (in JavaScript) that would write a sentence in a <p>
tag by writing its letters one by one with a 300ms pause between each letter, for exmaple. I've written the following:
var text = ["H", "e", "l", "l", "o", " ", "h", "o", "w", " ", "a", "r", "e", "y", "o", "u", "?"]
function typeText() {
var i = 0;
var interval = setInterval(function () {
var parag = document.getElementById("theParagraph");
var paragOldText = parag.innerText;
parag.innerText = paragOldText + text[i];
i++;
if (text.length == i)
clearInterval(interval);
}, 200)
}
<body>
<p id="theParagraph"></p>
<button id="typeButton" onclick="typeText()" style="padding:15px">Start typing the sentence</button>
</body>
如您所见,有一些 ""数组中的(空白)字符;问题是它没有写那些空格,所以句子应该是这样的:Hellohowareyou".我该如何解决这个问题?
As you can see, there are some " " (empty space) characters in the array; the problem is that it doesn't write those empty spaces, so the sentence would be like this: "Hellohowareyou". How do I solve this?
不要将表示用作数据. 将当前内容存储为单独的字符串,不要从 DOM 中提取它.这样您就不会依赖于浏览器如何存储元素的文本内容.
Don't use presentation as data. Store the current content as a separate string, don't pull it from the DOM. This way you're not dependent on how the browser stores the element's text content.
var text = ["H", "e", "l", "l", "o", " ", "h", "o", "w", " ", "a", "r", "e", "y", "o", "u", "?"]
function typeText() {
var i = 0;
var paragText = "";
var interval = setInterval(function () {
var parag = document.getElementById("theParagraph");
paragText += text[i];
parag.innerText = paragText;
i++;
if (text.length == i)
clearInterval(interval);
}, 200)
}
<body>
<p id="theParagraph"></p>
<button id="typeButton" onclick="typeText()" style="padding:15px">Start typing the sentence</button>
</body>
顺便说一句,同样的事情可以变得更简单:
As a side note, the same thing could be made a lot simpler:
var text = "Hello how are you?";
function typeText() {
var i = 0;
var interval = setInterval(function () {
var parag = document.getElementById("theParagraph");
parag.innerText = text.substr(0, i);
if (text.length == i)
clearInterval(interval);
i++;
}, 200)
}
<body>
<p id="theParagraph"></p>
<button id="typeButton" onclick="typeText()" style="padding:15px">Start typing the sentence</button>
</body>