在textarea中保留outputed div中的换行符

时间:2022-03-14 18:17:57

$("textarea").blur(function() {
  $("div").html($("textarea").val());
});

$("textarea").blur();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea style="height:50px;">
1. test
2. test
3. test
</textarea>

<div style="word-break: break-all;"></div>

I would like to make the text appear in div in the exact manner as it appears in textarea.

我想使文本以与textarea中出现的完全相同的方式显示在div中。

I've tried to css div with word-break, etc. but none has worked.

我试图用word-break等css div,但没有一个有效。

Note: specifically, I just want to know how to do it within a div.

注意:具体来说,我只是想知道如何在div中完成它。

2 个解决方案

#1


2  

Try setting white-space:pre; or white-space:pre-wrap; to the div.

尝试设置white-space:pre;或白色空间:预包装;到了div。

$("textarea").blur(function() {
  $("div").html($("textarea").val());
});

$("textarea").blur();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea style="height:50px;">
1. test
2. test
3. test
</textarea>

<div style="white-space:pre;"></div>

#2


0  

Pangloss does propose a solution, but it doesn't seem to be able to help you if you want them to be able to export it to HTML.

Pangloss确实提出了一个解决方案,但如果您希望它们能够将其导出为HTML,它似乎无法帮助您。

If so,

str = str.replace(/(?:\r\n|\r|\n)/g, '<br />');

Will do.

Reference: How do I replace all line breaks in a string with <br /> tags?

参考:如何使用
标记替换字符串中的所有换行符?

#1


2  

Try setting white-space:pre; or white-space:pre-wrap; to the div.

尝试设置white-space:pre;或白色空间:预包装;到了div。

$("textarea").blur(function() {
  $("div").html($("textarea").val());
});

$("textarea").blur();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea style="height:50px;">
1. test
2. test
3. test
</textarea>

<div style="white-space:pre;"></div>

#2


0  

Pangloss does propose a solution, but it doesn't seem to be able to help you if you want them to be able to export it to HTML.

Pangloss确实提出了一个解决方案,但如果您希望它们能够将其导出为HTML,它似乎无法帮助您。

If so,

str = str.replace(/(?:\r\n|\r|\n)/g, '<br />');

Will do.

Reference: How do I replace all line breaks in a string with <br /> tags?

参考:如何使用
标记替换字符串中的所有换行符?