Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to achieve a typewriting effect and my content consists of a lot of HTML entities. The problem with using .html() is that since it writes out each letter at a time, it will type out & then l then t then ; and finally it would change to <.

HTML

<p id="src">
&lt;!DOCTYPE html&gt;
&lt;!--[if lt IE 7]&gt;      &lt;html class=&quot;no-js lt-ie9 lt-ie8 lt-ie7&quot;&gt; &lt;![endif]--&gt;
&lt;!--[if IE 7]&gt;         &lt;html class=&quot;no-js lt-ie9 lt-ie8&quot;&gt; &lt;![endif]--&gt;
&lt;!--[if IE 8]&gt;         &lt;html class=&quot;no-js lt-ie9&quot;&gt; &lt;![endif]--&gt;
&lt;!--[if lt IE 9]&gt;      &lt;html class=&quot;no-js lt-ie9&quot;&gt; &lt;![endif]--&gt;
</p>
<p id="typed-paragraph">
    <span id="target"></span>
    <span id="typed-cursor">|</span>
</p>

CSS

#src {
    display: none;
}

jQuery

(function(){
    var srcText = $("#src").html();
        i = 0;
        result = srcText[i];
    setInterval(function() {
        if(i == srcText.length-1) {
            clearInterval(this);
            return;
        };
        i++;
        result += srcText[i].replace("
", "<br />");
        $("#target").html(result);
    }, 150); // the period between every character and next one, in milliseonds.
})();

You can see the example of it here http://jsfiddle.net/j9KF5/9/

But if I use .text() then I lose all the line breaks.

Ultimately, how I can either fix the entities problem or the line break problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
133 views
Welcome To Ask or Share your Answers For Others

1 Answer

You don't need to worry about the HTML entities nor any complex string replacing.

All you need is a little CSS:

#target {
    white-space: pre;
}

and use the .text() approach:

(function(){
    var srcText = $("#src").text().trim();
        i = 0;
        result = srcText[i];
    setInterval(function() {
        if(i == srcText.length-1) {
            clearInterval(this);
            return;
        };
        i++;
        result += srcText[i];
        $("#target").text(result);

    }, 150); // the period between every character and next one, in milliseonds.
})();

http://jsfiddle.net/mattball/vsb9F/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...