html的textarea中的文字怎么换行显示

我想在textarea中输入的文字,显示在网页中时,按照输入的时候的格式显示。
输入框中显示是这样的:两行文字有换行

clipboard.png

1、html如果这样写:

<div>
    <p>{{$article->content}}</p>
</div>

显示结果如截图所示:两行文字不会换行

clipboard.png

2、html中加一个white-space: pre;

.pre-text {
    white-space: pre;
}

html代码如下:

<div>
    <p class="pre-text">{{$article->content}}</p>
</div>

结果如下面截图:两行文字会换行,但会超出外面的div

clipboard.png

问题:
怎么让文本换行显示又不超出外层div?

阅读 39.7k
5 个回答
.pre-text {
        white-space: pre-wrap;
        word-wrap: break-word;
        word-break: break-all;
}

直接把换行符替换成br标签

function fixText(text) {
    var replaceRegex = /(\n\r|\r\n|\r|\n)/g;

    text = text || '';

    return text.replace(replaceRegex, "<br/>");
}

white-space: pre-line;
word-wrap: break-word;

white-space: pre;
white-space: pre-line;
word-wrap: break-word;

推荐问题