highlight.js
需要的文件
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/default.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js"></script>
【示例】
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<pre><code>
int main(){
return 1;
}
</code></pre>
<pre><code>
window.onload = function() {
let blocks = document.querySelectorAll("pre code");
for (let i = 0, len = blocks.length; i < len; i++) {
hljs.highlightBlock(blocks[i]);
}
}
</code></pre>
<link rel="stylesheet" href="highlight.min.css">
<script src="highlight.min.js"></script>
<!-- 使用原生 JS 实现 -->
<script>
window.onload = function() {
let blocks = document.querySelectorAll("pre code");
for (let i = 0, len = blocks.length; i < len; i++) {
hljs.highlightBlock(blocks[i]);
}
}
</script>
<!-- 使用 jQuery 实现 -->
<!-- <script src="jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function() {
$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
});
</script> -->
</body>
</html>