gpt4 book ai didi

javascript - InnerText 属性忽略空格

转载 作者:技术小花猫 更新时间:2023-10-29 11:55:44 28 4
gpt4 key购买 nike

我正在尝试编写一个函数(在 JavaScript 中),它将在 <p> 中写一个句子例如,通过在每个字母之间停顿 300 毫秒,一个接一个地写入其字母来标记。我写了以下内容:

        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”。我该如何解决这个问题?

最佳答案

不要将表示用作数据。将当前内容存储为单独的字符串,不要从 DOM 中提取它。这样您就不会依赖于浏览器如何存储元素的文本内容。

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>


作为旁注,同样的事情可以变得更简单:

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>

关于javascript - InnerText 属性忽略空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47768523/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com