使用jQuery的.text()方法时如何保持换行符?

ani*_*ita 26 html javascript css jquery

我正在尝试实现打字效果,我的内容包含很多HTML实体.使用的.html()的问题是,因为它写出每次打开一个字母,它会打出来&,然后lt然后;,最后再变成<.

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>
Run Code Online (Sandbox Code Playgroud)

CSS

#src {
    display: none;
}
Run Code Online (Sandbox Code Playgroud)

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("\n", "<br />");
        $("#target").html(result);
    }, 150); // the period between every character and next one, in milliseonds.
})();
Run Code Online (Sandbox Code Playgroud)

你可以在这里看到它的例子 http://jsfiddle.net/j9KF5/9/

但是,如果我使用.text(),那么我将失去所有的换行符.

最终,我如何解决实体问题或换行问题?

Mat*_*all 33

您无需担心HTML实体或任何复杂的字符串替换.

你需要的只是一个小CSS:

#target {
    white-space: pre;
}
Run Code Online (Sandbox Code Playgroud)

并使用.text()方法:

(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.
})();
Run Code Online (Sandbox Code Playgroud)

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

  • 另一种选择是“whitespace: pre-wrap”,它可以避免长行使框变宽 (3认同)

orc*_*man 14

对于那些正在寻找问题标题实际问题的人(这是我如何进入这个页面,"如何在使用jQuery的text()方法时保持换行符"),你可以使用这样的东西:

(function($){
   $.fn.innerText = function(msg) {
         if (msg) {
            if (document.body.innerText) {
               for (var i in this) {
                  this[i].innerText = msg;
               }
            } else {
               for (var i in this) {
                  this[i].innerHTML.replace(/&amp;lt;br&amp;gt;/gi,"n").replace(/(&amp;lt;([^&amp;gt;]+)&amp;gt;)/gi, "");
               }
            }
            return this;
         } else {
            if (document.body.innerText) {
               return this[0].innerText;
            } else {
               return this[0].innerHTML.replace(/&amp;lt;br&amp;gt;/gi,"n").replace(/(&amp;lt;([^&amp;gt;]+)&amp;gt;)/gi, "");
            }
         }
   };
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

现在调用$('.some-class').innerText()来保存包含换行符的文本.