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

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

问题描述

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

第一天1-一个苹果.2-一橙.3-两杯牛奶.

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

第一天 1- 一个苹果.2-一橙.3- 两杯牛奶.

如何使它看起来与 <textarea> 中的一样?

解决方案

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

textarea {高度:70px;}标签 {空白:预包装;}

<textarea>第一天1-一个苹果.2-一橙.3-两杯牛奶.</textarea><br><br><标签>第一天1-一个苹果.2-一橙.3-两杯牛奶.</label>

<小时>

除了 white-space 属性结合换行符(例如 )之外,HTML 换行的方法是使用
;
,在这里添加一个小示例,它们是如何工作和不同的.

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

var sample_script = document.querySelector('.sample.script');var name = "一二三";var name1 = name.replace(//g, '
');var name2 = name.replace(//g, '<br>');sample_script.innerHTML += name1;sample_script.innerHTML += "<br><br>";sample_script.innerHTML += name2;

div.pre {空白:pre;}/* 这个演示的样式 */身体{显示:弯曲;}.sample {flex: 1;边距:0 20px;}

<div class="sample inline">排队<小时>

一二三</div><div class="pre">一二三</div></div><div class="示例脚本">脚本<小时></div>

I put text in a <textarea> like this:

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

But it shows in a <label> like this:

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

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

解决方案

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>


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

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, '
');
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天全站免登陆