如何显示带有带换行符的文本的标签? [英] How to display a label having text with line breaks?

查看:133
本文介绍了如何显示带有带换行符的文本的标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将文本放在<textarea>中,如下所示:

I put text in a <textarea> like this:

First day
1-one apple.
2-one orange.
3-two cups of milk.

但是它在<label>中显示如下:

First day 1- one apple. 2-one orange. 3- two cups of milks.

如何使其与<textarea>中的外观相同?

How do I make it look the same as in a <textarea>?

推荐答案

给出标签white-space: pre-wrap,它将像文本区域一样中断换行

Give the label white-space: pre-wrap and it will break line as the text area does

textarea {
  height: 70px;
}
label {
  white-space: pre-wrap;
}

<textarea>
  First day
1-one apple.
2-one orange.
3-two cups of milk.
</textarea>

<br><br>

<label>
  First day
1-one apple.
2-one orange.
3-two cups of milk.
</label>

除了white-space属性和换行符(例如\n)之外,HTML换行的方式是使用<br>,在此处添加一个小示例,说明它们的工作原理和区别.

Besides the white-space property combined with a new line character (e.g. \n), the HTML way to break line is using <br>, add here is a small sample how they work and differ.

请注意,即使使用,也可以保留空格. white-space: pre,如内联"代码示例中所示

Note, even space's are preserved using e.g. white-space: pre, as seen in the "inline" code sample

var sample_script = document.querySelector('.sample.script');

var name = "One Two Three";
var name1 = name.replace(/ /g, '\n');
var name2 = name.replace(/ /g, '<br>');

sample_script.innerHTML += name1;
sample_script.innerHTML += "<br><br>";
sample_script.innerHTML += name2;

div.pre {
  white-space: pre;
}


/*  styling for this demo  */
body {display: flex;}
.sample {flex: 1; margin: 0 20px;}

<div class="sample inline">

  Inline
  <hr>
  <div>
    One
    Two
    Three
  </div>

  <div class="pre">
    One
    Two
    Three
  </div>
</div>

<div class="sample script">
  Script
  <hr>

</div>

这篇关于如何显示带有带换行符的文本的标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆