空格被 InnerText 属性忽略 [英] Empty spaces are ignored by the InnerText property

查看:47
本文介绍了空格被 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>

这篇关于空格被 InnerText 属性忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆