Html 在 textarea 中突出显示.js

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19346975/
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-08-29 14:24:54  来源:igfitidea点击:

Highlight.js in textarea

javascripthtmlsyntax-highlightinghighlighthighlight.js

提问by Kivi Freak

So i have been struggeling to use highlight.js in a text area since obviously this doesn't work:

所以我一直在努力在文本区域中使用 highlight.js 因为显然这不起作用:

<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
<link rel="stylesheet" href="styles/default.css">
<script src="highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
</head>
<body>
<form>
    JavaScript Injection: <br> 
<pre>
<code>
<textarea name="js_execute" cols="50" rows="10" "></textarea>
</code>
</pre>
<input type="button" name="Inject_Execute_Button" value = "Inject" onclick="executeJS()" >
</form>

<script type="text/javascript">
 function executeJS()
 {
     alert("Wohoo");
 }
</script>


<style type ="text/css">

</style>
</body>
</html>

I'm pretty sure there's an easy answer to this so i won't explain it in too detail but at the end i would prefer to have code typed into the textarea highlighted in JavaScript.

我很确定对此有一个简单的答案,所以我不会详细解释它,但最后我更愿意将代码输入到用 JavaScript 突出显示的 textarea 中。

回答by Pierre-Antoine

You might want to look at http://ace.c9.io/, which does syntax highlighting, but is specifically aimed at editing.

您可能想查看http://ace.c9.io/,它进行语法高亮显示,但专门针对编辑。

Note however that it does not use textareaeither, probably for the same reasons mentioned by @isagalaev.

但是请注意,它不使用textarea任何一个,可能与@isagalaev 提到的原因相同。

回答by isagalaev

The simple answer is that highlight.js won't work in a textarea because its content is not part of the page and it simply can't have any styles by itself. If you want a text editor in a browser with highlight.js you probably should look into contenteditableso you could call hljs.highlight()on its content on every change. However I'm not aware of any successful implementation of this.

简单的答案是highlight.js 不能在textarea 中工作,因为它的内容不是页面的一部分,而且它本身不能有任何样式。如果你想要一个带有 highlight.js 的浏览器中的文本编辑器,你可能应该查看contenteditable以便你可以hljs.highlight()在每次更改时调用它的内容。但是我不知道有任何成功的实施。

回答by RubenCaro

I understand from the usage pagethat it will highlight the code inside the <pre><code>tags. Not from any other container.

我从使用页面了解到它将突出显示<pre><code>标签内的代码。不是来自任何其他容器。

In your example, it would highlight the html of the textarea itself, as it is inside the <pre><code>tags, and not de contents of the textarea.

在您的示例中,它会突出显示 textarea 本身的 html,因为它位于<pre><code>标签内,而不是 textarea 的内容。