问题
So i have been struggeling to use highlight.js in a text area since obviously this doesn't work:
<!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.
回答1:
You might want to look at http://ace.c9.io/, which does syntax highlighting, but is specifically aimed at editing.
Note however that it does not use textarea
either, probably for the same reasons mentioned by @isagalaev.
回答2:
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 contenteditable so you could call hljs.highlight()
on its content on every change. However I'm not aware of any successful implementation of this.
回答3:
I understand from the usage page that it will highlight the code inside the <pre><code>
tags. Not from any other container.
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.
来源:https://stackoverflow.com/questions/19346975/highlight-js-in-textarea