您可以简单地使用 class 属性在 highlightjs 中指定语言。
例如,如果您要突出显示 python 代码
<pre class="python">
<code>
print "Hello"
</code>
</pre>
编辑:
创建一个名为 highlightcon.min.js 的文件将其与您的 html 文件 <script src="highlightcon.min.js"></script> 链接并将您配置的对象粘贴到 highlightcon.min.js
如果您想定义自己的语言,也可以使用实时语法高亮,您可以使用 ace 编辑器,因为高亮 js 不提供您正在寻找的功能...
在你的index.html 使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Editor</title>
<link rel="stylesheet" href="views/style.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.12/ace.js"></script>
</head>
<body>
<!-- Elements -->
<div id='container'>
<div id="editor">
</div>
<iframe id='iframe' frameBorder="0">
</iframe>
</div>
<!-- Javascript -->
<script src="script.js"></script>
</body>
</html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.12/ace.js">是王牌编辑器cdn...
然后在您的script.js 文件中
function update()
{
var idoc = document.getElementById('iframe').contentWindow.document;
idoc.open();
idoc.write(editor.getValue());
idoc.close();
}
function setupEditor()
{
window.editor = ace.edit("editor");
editor.setTheme("ace/theme/monokai");
editor.getSession().setMode("ace/mode/python");
editor.getSession().on('change', function() {
update();
});
editor.focus();
editor.setOptions({
fontSize: "16pt",
showLineNumbers: true,
showGutter: false,
vScrollBarAlwaysVisible:true,
enableBasicAutocompletion: true, enableLiveAutocompletion: true
});
editor.setShowPrintMargin(false);
editor.setBehavioursEnabled(true);
}
setupEditor();
update();
const elementToObserve = document.querySelector("#editor");
在这里,您定义语言 editor.getSession().setMode("ace/mode/python");,您可以在下面的script.js 中找到它。
你可以使用editor.session.setMode("ace/mode/" + language),只是你需要在编写这个命令之前指定这样的语言
var language = "python"
这也提供了实时语法高亮显示..