2
4

2 回答 2

6

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:

  1. pre is the equivalent of wrapping the whole thing in a <pre> tag.

  2. The difference between pre and pre-wrap is whether extra linebreaks will be added as needed for long lines.

  3. The difference between pre-wrap and pre-line is whether all whitespace is preserved (including spaces), or only newlines.

  4. 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 ")
于 2013-08-03T06:14:43.710 回答
0

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;
}
于 2013-08-03T06:14:47.760 回答