且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-24 22:11:34

您不需要担心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/