问题
在源自 <textarea>
的网页上显示文本的简单有效模式是什么?元素同时保留原始格式?
目标
我们的目标是让客户可以在 <textarea>
中输入任何感觉。并让他们以后能够查看它,并保留他们使用的所有字符和换行符。
任何使用 Javascript、Jquery 或 Backbone 的东西都很棒。
更多信息
我尝试过的三种(有缺陷的)方法:
- 使用
jQuery('element').html()
显示文本- 此方法的问题在于,客户端可能选择输入文本区域的与 html 相关的字符被解释为 html,例如
>
和<
- 此方法的问题在于,客户端可能选择输入文本区域的与 html 相关的字符被解释为 html,例如
- 使用
jQuery('element').text()
显示文本- 此方法的问题是客户选择使用的所有换行符都被丢弃。
- 以只读方式显示文本
<textarea>
元素。- 这个方法的问题是很难得到
<textarea>
。以扩展到文本的确切大小。在有吸引力的格式方面也有一些不足之处。
- 这个方法的问题是很难得到
最佳答案
str.replace(/\x26/g,'\x26amp;') // first do all & to &
.replace(/\x3c/g,'\x26lt;') // next do < to <
.replace(/\r\n|\n/g,'\x3cbr>'); // finally replace new lines with <br>
// Note: I chose hex char code to exclude the 'risky' characters from the code,
// that way they are also safe for inline-scripts (in older browsers).
// Also, I used local setting char-notation, not unicode,
// as they are the same for this purpose (and it saves some chars).
- 注意:替换顺序很重要。
- 另请注意:此序列没有结束并尝试通过查找 'HTML equivalent to …that DOES break; 来保留空白(又名,避免 HTML 的空白折叠功能) '(并用它替换空格)因为使用
pre
要简单得多用于保存内容的标记(对于较旧的浏览器,尤其是 IE<9 似乎更好)或禁用 CSS 中的空白折叠功能:div.preview {white-space: [pre|pre-wrap];}
简单示例(live jsFiddle here):
<textarea style="width:98%" onkeyup="
this.nextSibling.innerHTML=this.value.replace(/\x26/g,'\x26amp;')
.replace(/\x3c/g,'\x26lt;')
.replace(/\r\n|\n/g,'\x3cbr>');
"></textarea><pre></pre>
请注意,您可能还想 Hook onchange
等等。另外,您可能希望有一个单独的函数并缓存输出(和输入)元素。
你可以让它变得更加困难,例如只替换 &
当绝对需要时,同样适用于 <
.
您也可以将所有不需要的(非“ASCII”)字符转换为它们的 unicode HTML 实体等价物,但所有这些对于简单预览来说似乎有点矫枉过正,因为您可能不想在此(过度)中提交用户数据有效)html 标记。一个简单的例子是:
.replace(/[^\u0020-\u007e]/g, function(m){return '\x26#'+m.charCodeAt(0)+';';})
希望这能让您入门。
编辑 1: 另请查看 demo jsFiddle v2和 demo jsFiddle v3对于一些更高级的示例,例如:
( // START HTML encoder hookup
function(enc, e1, e2, e3){
(e1.onkeyup = function(){
e3.innerHTML = e2.value = enc(e1.value);
})();
}( // IIFE Passing encoder and elements
(function(){ //HTML enc
var amp=/\x26/g , lte=/\x3c/g , eol=/\r\n|\n/g
, noASCI=/[^\u0020-\u007e]/g
, toUCPd=function(m){ return '\x26#'+ m.charCodeAt(0) +';'; }
;
return function(s){return(
s.replace(amp, '\x26amp;')
.replace(lte, '\x26lt;')
.replace(eol, '\x3cbr>')
.replace(noASCI, toUCPd) //optional
);};
}
)() //IIFE returns HTML enc
, document.getElementsByTagName('textarea')[0]
, document.getElementsByTagName('textarea')[1]
, document.getElementsByTagName('pre')[0]
)
); // END HTML encoder hookup
/* Corresponding demo html:
Input:<br>
<textarea>	<this is a tab char & these ☺ë non-'ASCII'
continue to to type here</textarea><br>
Generated HTML code:<br>
<textarea>code output</textarea><br>
HTML output in pre:<br>
<pre>html output</pre>
*/
编辑 2: 差点忘了,你可以看看(古怪,被遗忘但仍然有效) xmp
-tag .这将一直有效,直到用户键入 </xmp
.旧版 IE 的注意事项:替换整个 xmp 元素而不是设置/覆盖它的 innerHTML
(因为这至少在 IE6 中不起作用)。然而,如前所述,这个 xmp
有很多怪癖。 -关于不同浏览器上的框布局、溢出等的标签!
关于javascript - 用于在源自 <textarea> 的网页上显示文本的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25586580/