我有一个表单,其中包含一个 <textarea>....</textarea>
字段。在保存文本后,它会在另一个表单中以段落 <p>...</p>
的形式显示结果。
问题是它将所有行连接在一起显示为一行。
当我去编辑字段时,行被正确地呈现(多行)。
如何将所有行显示为输入在 <textarea>....</textarea>
中的格式?
Using <br>
tags
You need to convert your new lines to <br>
tags while displaying the data in your paragraph <p>
. Something on the following lines will help-
var value = $('.textareaClass').val();
$('.paragraphClass').html('<p>'+(value.replace(/\r?\n/g,'<br/>'))+'</p>');
Using CSS rules
Another simpler way to do this is by using CSS, in which, you simply have to add the rule white-space: pre-wrap
to your <p>
class. For example, if your paragraph has class text-content
then you simply have to do-
.text-content {
white-space: pre-wrap;
}
DEMO: JSFiddle
You need to replace newline with <br>
to provide new line in html
$('#text').on('input', function() {
$('#res').html(this.value.replace(/\r?\n/g, '<br>'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id=text></textarea>
<div id=res></div>
p
标签包装每个字符串。
$('#text').on('input', function() {
$('#res').html('<pr>' + this.value.split(/\r?\n/).join('</p><p>') + '</p>');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id=text></textarea>
<div id=res></div>
<pre>
替代 <p>
,并让它与 <textarea>
具有相同的宽度。同时添加了额外的参数以复制换行和滚动行为:
function test(){
var thetarget = document.getElementById("b");
thetarget.innerHTML = document.getElementById("a").value;
thetarget.scrollTop = thetarget.scrollHeight;
}
body {
background: lavender;
}
textarea, pre {
width: 200px;
height: 176px;
white-space: -moz-pre-wrap;
white-space: -pre-wrap;
white-space: -o-pre-wrap;
white-space: pre-wrap;
word-wrap: break-word;
float: left;
margin-left: 10px;
margin-top: 0;
overflow-y: auto;
}
<textarea id=a oninput="test()"></textarea><pre id=b></pre>