jQuery 使用换行符将 textarea 的文本复制到 div 中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18145682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Copying text of textarea into div with line breaks
提问by Kamal
I am tying to make a simple effect using keyup()
in jQuery. I just want that when user types into the textarea
then the text which user types will copy to another div named .content
. When I press enterin textarea a new line is created but in my div the text is showing in the same line. My code is below or you can see demo here: http://jsfiddle.net/Pqygp/
我想keyup()
在 jQuery 中使用一个简单的效果。我只是希望当用户输入时,用户输入的textarea
文本将复制到另一个名为.content
. 当我enter在 textarea 中按下时,会创建一个新行,但在我的 div 中,文本显示在同一行中。我的代码在下面,或者你可以在这里看到演示:http: //jsfiddle.net/Pqygp/
$('.content:not(.focus)').keyup(function(){
var value = $(this).val();
var contentAttr = $(this).attr('name');
$('.'+contentAttr+'').html(value);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea name="mas" rows="15" class="content"></textarea>
<p> </p>
<div class="mas" >Texts Comes here</div>
回答by JJJ
Add a white-space: pre-wrap
rule to the div's CSS.
white-space: pre-wrap
向 div 的 CSS添加规则。
.mas {
white-space: pre-wrap;
}
回答by SmokeyPHP
You need to convert the literal newlines into <br>
tags for proper output in the DIV.
您需要将文字换行符转换为<br>
标签,以便在 DIV 中正确输出。
$('.'+contentAttr+'').html(value.replace(/\r?\n/g,'<br/>'));
Shown in your code below:
显示在下面的代码中:
$('.content:not(.focus)').keyup(function(){
var value = $(this).val();
var contentAttr = $(this).attr('name');
$('.'+contentAttr+'').html(value.replace(/\r?\n/g,'<br/>')); //convert newlines into <br> tags
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <textarea name="mas" rows="15" class="content"></textarea> <p> </p> <div class="mas" >Texts Comes here</div>
回答by Dallas
回答by Gautam3164
回答by dominik791
If you use React:
如果你使用 React:
render() {
const nbOfTextareaRows = this.state.textareaValue.split('\n').length;
return (
<textarea
value={this.state.textareaValue}
onChange={e => this.setState({ textareaValue: e.target.value })}
rows={nbOfTextareaRows}
/>
);
}