如何在jQuery中使用.text()方法时保持换行符? [英] How to keep line breaks when using .text() method for jQuery?
问题描述
我想要达到打字效果,我的内容包含许多HTML实体。使用.html()的问题是,因为它每次写出每个字母,它会输出&
然后 l
然后 t
然后;
,最后它将更改为< code>。
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">
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if lt IE 9]> <html class="no-js lt-ie9"> <![endif]-->
</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("\n", "<br />");
$("#target").html(result);
}, 150); // the period between every character and next one, in milliseonds.
})();
你可以看到这里的例子
http://jsfiddle.net/j9KF5/9/
You can see the example of it here http://jsfiddle.net/j9KF5/9/
但是如果我使用.text(),那么我失去所有的换行符。
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?
推荐答案
您不需要担心HTML实体或任何复杂的字符串替换。
You don't need to worry about the HTML entities nor any complex string replacing.
您需要的只是一些CSS:
All you need is a little CSS:
#target {
white-space: pre;
}
并使用 .text c $ c>方法:
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/
这篇关于如何在jQuery中使用.text()方法时保持换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!