admin管理员组

文章数量:1394046

I have a <textarea> element. When the user fills it, you can see the spaces they made and when they pressed Enter to jump to the next line.

This is great, but when I see the HTML output, the result differs. It is an endless sentence without line breaks.

Using only HTML or JavaScript, how can I fix this?

I have a <textarea> element. When the user fills it, you can see the spaces they made and when they pressed Enter to jump to the next line.

This is great, but when I see the HTML output, the result differs. It is an endless sentence without line breaks.

Using only HTML or JavaScript, how can I fix this?

Share Improve this question edited Nov 5, 2012 at 8:32 Pekka 450k148 gold badges987 silver badges1.1k bronze badges asked Nov 5, 2012 at 8:28 user1799565user1799565 591 silver badge7 bronze badges 3
  • 1 Your question is very vague. Please post some code if you want to get a response – Mihai Commented Nov 5, 2012 at 8:30
  • 1 Wele to SO. Please share your code or what you have tried to get good answers!!! – Rahul Tripathi Commented Nov 5, 2012 at 8:31
  • 4 I don't think it's vague. The OP wants the line break behaviour in the textarea to match that of the HTML output. He doesn't want to use a full-blown WYSIWYG editor to fix the problem, and he's right. – Pekka Commented Nov 5, 2012 at 8:31
Add a ment  | 

2 Answers 2

Reset to default 9

You probably want something like:

<p style="white-space: pre-wrap"></p>
<p style="white-space: pre"></p>
<pre></pre>

pre-wrap:
Whitespace is preserved by the browser. Text will wrap when necessary, and on line breaks 
pre:
Whitespace is preserved by the browser. Text will only wrap on line breaks Acts like the <pre> tag in HTML

If you are just taking what is entered in a textarea and outputing it as html, you would see this. For starters, you could replace all spaces with &nbsp; and all newlines with <br>. Or put the output in <pre> tags. (In either case, you will also want to replace some other characters with entities too.)

本文标签: javascriptHow do I make the whitespace behaviour in a lttextareagt and a HTML preview matchStack Overflow