从文本区域保存多行文本

11

我有一个表单,其中包含一个 <textarea>....</textarea> 字段。在保存文本后,它会在另一个表单中以段落 <p>...</p> 的形式显示结果。

问题是它将所有行连接在一起显示为一行。

当我去编辑字段时,行被正确地呈现(多行)。

如何将所有行显示为输入在 <textarea>....</textarea> 中的格式?

3个回答

9
这个问题有两种解决方式-
  1. 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>');
    
  2. 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

希望这有所帮助!

2

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>


@AbdallahSabri:很高兴能帮忙 :) - Pranav C Balan

1
使用 <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>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接