在做一些项目的时候,经常会用到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>