javascript 如何在textarea内预格式化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9763579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:45:38  来源:igfitidea点击:

How to preformat inside textarea

javascripthtmltextareapre

提问by jmnwong

I was wondering if it were possible to preformat text that is inside a textarea. Right now I have a textarea code that I want to add syntax highlighting and also add linenumbers so I am trying to wrap the text inside a pre tag. Is this correct or should I be doing something completely different?

我想知道是否可以预先格式化 textarea 内的文本。现在我有一个 textarea 代码,我想添加语法突出显示并添加行号,所以我试图将文本包装在 pre 标签中。这是正确的还是我应该做一些完全不同的事情?

<textarea id="conversation" class="codebox" style="font-family:courier;">
<pre class="brush: js;">//  Start typing...</pre>
</textarea>

采纳答案by Jared Farrish

textareas are not able to render content like you're wanting to do, they only display text. I would suggest an in-browser code editor. A good one is CodeMirror, which is fairly easy to use:

textareas 无法像您想要的那样呈现内容,它们只显示文本。我建议使用浏览器内的代码编辑器。一个好的是CodeMirror,它相当容易使用:

HTML

HTML

<textarea id="code" name="code">
// Demo code (the actual new parser character stream implementation)

function StringStream(string) {
  this.pos = 0;
  this.string = string;
}
...
</textarea>

Javascript

Javascript

var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
    lineNumbers: true,
    matchBrackets: true
});

And CodeMirror insert an editable block with that content within the new editor.

并且 CodeMirror 在新编辑器中插入一个包含该内容的可编辑块。

There are other options. Wikipedia has a comparison of Javascript-based source code editorsentry.

还有其他选择。维基百科有一个比较基于JavaScript的源代码编辑器条目

回答by Dallas Lones

Having the Pre tag contain the textarea works in Chrome

让 Pre 标签包含 textarea 在 Chrome 中工作

回答by Jukka K. Korpela

The textareaelement content is treated as preformatted in implementations, though browsers by default line wrap the text if a line is longer than specified by the colsattribute. The wrapping can be disabled using the nonstandard but widely supported attribute wrap=off.

所述textarea元素含量被视为在实现预格式化,虽然由缺省线浏览器自动换行,如果线的长度超过由指定的cols属性。可以使用非标准但广泛支持的属性来禁用包装wrap=off

The textarea element is not adequate for mere display of content, though. Neither is it suitable for setting up an input editor with formatting features, since all markup inside textareais taken literally.

但是, textarea 元素不足以仅显示内容。它也不适合设置具有格式化功能的输入编辑器,因为里面的所有标记textarea都是按字面意思进行的。