Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

javascript - How to keep line breaks when using .text() method for jQuery?

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

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

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...