在< pre>中获得换行符标签 [英] getting linebreaks in <pre> tags

查看:127
本文介绍了在< pre>中获得换行符标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建基于用户输入到textarea的注释字段。但是当我使用< pre>标签我无法告诉它在评论视图中正确包装。



我并未坚持使用< pre>标记是否有更好的方法。我只选择使用它的原因是为了让用户添加换行符和空格。



我注意到< pre>有一个名为width的属性,但W3注意到它已被弃用,并且它只会在如此多的字符之后被打破,这也不是理想的。 (它也不适用于IE浏览器。)



有什么建议吗?

解决方案

通常的做法是将输入中的单个换行符转换为< br />。 (Double-newlines通常会引入一个新的< p>元素。)但这并不包括多空白运行;如果你需要保留这些空间,你可以用一个空格和一个非空格空格('','\xA0'或'&#160;'作为字符引用)替换每个双空间序列。 p>

有一种CSS方式可以保留字面换行符和空格,但是当行长度太短时仍然可以换行:

  white-space:pre-wrap; 

然而,这个CSS 2.1和CSS 3属性值不支持跨浏览器的原名。 Webkit(Safari,Chrome)选择它;为了让它在其他流行的浏览器下运行,你必须添加:

  white-space:-moz-pre-wrap ; 
空格:-o-pre-wrap;
word-wrap:分词;

'word-wrap'适用于IE,它一如既往地有自己的做事方式。

I'm creating comment fields which are based on user input into textarea. But when I use <pre> tags I can't tell it to wrap properly inside the comments view.

I'm not stuck on using <pre> tags if there is a better way of doing it. Only reason I chose to use it was to keep linebreaks and whitespaces added by user.

I noticed there is a property called "width" for <pre>, but W3 notes it as deprecated, and it only breaks after so and so many characters, which isn't ideal either. (It also doesn't work with IE at all.)

Any suggestions?

解决方案

The usual approach is to convert single newlines in the input to "<br />". (Double-newlines would normally introduce a new "<p>" element.) This doesn't cover multiple-whitespace-runs though; if you need to preserve those, you could replace each two-space sequence with a space and a non-breaking space ('  ', ' \xA0', or ' &#160;' as a character reference).

There is a CSS way you can retain literal newlines and whitespaces but still wrap when the line length is too short:

white-space: pre-wrap;

However this CSS 2.1 and CSS 3 property value is not supported cross-browser under its original name. Webkit (Safari, Chrome) picks it up; to get it to work under the other popular browsers, you have to add:

white-space: -moz-pre-wrap;
white-space: -o-pre-wrap;
word-wrap: break-word;

The ‘word-wrap’ is for IE, which as always has its own way of doing things.

这篇关于在&lt; pre&gt;中获得换行符标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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