JavaScript忽略了文本的最后一排破裂。(Elem.val())
我正在尝试将文本方面的值输出到PRE(或带有白空间的Div:pre on to Chip)中。一切都很好,但是它跳过了最后的线路破裂。因此,如果添加文本和线路破坏,它将不会显示线路破坏。如果添加文本和两个线路断开,它将显示文本和一个线路断开。 因此,看起来文本正在修剪。 谁能建议为什么会发生这种情况以及如何解决?
function starter(e) {
$("#output").text(e);
}
$('#textin').on('input',function(){
starter($('#textin').val())
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="textin"></textarea>
<pre id="output" style="border:1px solid black"></pre>
I'm trying to output a textarea value into a pre (or a div with white-space:pre for that matter). All works well, but it skips the last linebreak. So, if you add text and a linebreak, it won't display the linebreak. If you add text and two linebreaks, it displays text and one linebreak.
So, it looks like the text is being trimmed.
Can anyone suggest why this is happening and how to solve it?
function starter(e) {
$("#output").text(e);
}
$('#textin').on('input',function(){
starter($('#textin').val())
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="textin"></textarea>
<pre id="output" style="border:1px solid black"></pre>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我在阅读后找到了答案
在段落中时忽略了元素?。
浏览器会休息一段时间,而不是“线路结束”。
考虑到这一点;这个半十分的技巧可以完成这项工作,增加了一个额外的线路休息:
I found an answer after reading
When are <br> elements ignored when within a paragraph?.
Browsers take a line break not as a line break, but more like 'end of line'.
With that in mind; this semi-dirty trick does the job, adding an extra line break:
最简单的解决方案是简单地将您插入文本插入以下CSS属性中的元素进行样式:
此属性会导致匹配元素中的空格和新线的处理方式与
&lt; textarea&gt;
中的方式相同。也就是说,连续的白道不会崩溃,并且在显式新线时断开线(但如果超过元素的宽度,也会自动包装)。The easiest solution is to simply style the element you're inserting the text into with the following CSS property:
This property causes whitespace and newlines within the matching elements to be treated in the same way as inside a
<textarea>
. That is, consecutive whitespace is not collapsed, and lines are broken at explicit newlines (but are also wrapped automatically if they exceed the width of the element).