2 回答
Your question is a little unclear, but I'm assuming you want to keep the line breaks that are included in the string - rather than the browser default of ignoring them completely.
You'll want one of the pre
options for the white-space
property.
/* Display text exactly as entered */
white-space: pre;
/* Display as entered, plus extra linebreaks as needed for long lines */
white-space: pre-wrap;
/* Display newlines as entered, plus extra linebreaks as needed for long lines */
white-space: pre-line;
Some notes about the differences:
pre
is the equivalent of wrapping the whole thing in a<pre>
tag.The difference between
pre
andpre-wrap
is whether extra linebreaks will be added as needed for long lines.The difference between
pre-wrap
andpre-line
is whether all whitespace is preserved (including spaces), or only newlines.pre-line
is the equivilant of replacing all newlines with<br>
tags.
You can see a comparison of the different styles here: http://jsfiddle.net/Gcexh/
The other problem you will encounter is that you've got a linebreak between the last 2 lines of your input when you probably don't necessarily want a linebreak there.
You can fix that by dropping any single-newlines, and only keeping around the double-newlines like the ones that separate the first two lines.
This would ideally be done on the server side, but can also be done in javascript like this:
(with thanks to @JanDvorak):
text = text.replace(/(\n\s*\n)|\n/g, "$1 ")
I don't think there is a way to do it with css. The javascript way:
var myStr = "Your multiline\n\nstring...";
for (;;)
{
if (myStr.indexOf("\n") != -1)
myStr = myStr.replace("\n", " ");
else
break;
}