css--文本换行最简单的实现方式

在做一些项目的时候,经常会用到textarea来录入内容,之后再将其以其他标签展示出来。

在textarea中含有空格键、换行键的时候,如果直接上传给服务器,之后在返回的数据中,如果将数据再次以textarea的值来显示,空格键和换行会依然保留,但是如果以其他标签的时候为什么就没有保留空格、换行呢?

实际上并不是其他标签没有保留,而是因为你没有设置属性white-space:
white-space 属性设置如何处理元素内的空白。

描述
normal默认。空白会被浏览器忽略。
pre空白会被浏览器保留。其行为方式类似 HTML 中的 <pre> 标签。
nowrap文本不会换行,文本会在在同一行上继续,直到遇到 <br> 标签为止。
pre-wrap保留空白符序列,但是正常地进行换行。
pre-line合并空白符序列,但是保留换行符。
inherit规定应该从父元素继承 white-space 属性的值。

在任意标签上设置white-space: pre-wrap;就可以保证是按照在textarea中输入的格式来显示内容的,虽然设置white-space: pre;也可保留textarea中的空白,但是如果其他标签的宽度比textarea的宽度小的时候就会出现内容显示不全、不会自动换行的问题。
white-space: pre-wrap;和white-space: pre-line;的效果很相近,都会在标签宽度不足的时候自动换行,但是white-space: pre-wrap;会保留中的所有空白符,white-space: pre-line;会将多个空格合并为一个空格。

下面给出一个例子,大家可以尝试一下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>文本换行</title>
<script src="http://apps.bdimg.com/libs/jquery/1.11.3/jquery.js"></script>
<style>
.text {width: 500px;height: 100px;background: #eee;white-space: normal;}
</style>
</head>
<body>
<textarea name="text" rows="3" placeholder="文本换行" style="width: 800px;" id="textarea"></textarea>
<button type="button" id="btnGetText">点击获取文本</button>
<button type="button" id="btnSetNormal">normal</button>
<button type="button" id="btnSetPre">pre</button>
<button type="button" id="btnSetNowrap">nowrap</button>
<button type="button" id="btnSetPreWrap">pre-wrap</button>
<button type="button" id="btnSetPreLine">pre-line</button>
<div class="text"></div>
<script>
$("#btnGetText").on("click", function(){
    $(".text").html($("#textarea").val());
});
$("#btnSetNormal").on("click", function(){
    $(".text").css("white-space", "normal");
});
$("#btnSetPre").on("click", function(){
    $(".text").css("white-space", "pre");
});
$("#btnSetNowrap").on("click", function(){
    $(".text").css("white-space", "nowrap");
});
$("#btnSetPreWrap").on("click", function(){
    $(".text").css("white-space", "pre-wrap");
});
$("#btnSetPreLine").on("click", function(){
    $(".text").css("white-space", "pre-line");
});
</script>
</body>
</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值