Code Prettify 是 Google 的一款代码高亮js插件,它支持自动识别常用的语言,同时可以支持 Markdown 的语法。
Prettify 引用方式有两种,分别是自动引入和手动引入,如果无需定制,推荐使用自动引入,一行代码即可搞定。
自动引入
使用一行代码搞定JS与CSS的引入
<script src="https://cdn.jsdelivr.net/gh/google/code-prettify@master/loader/run_prettify.js"></script>
同时,此URL地址可以传参数,用于拓展一些不能自动识别的语言和设置主题。
参数 | 默认 | 注解 |
---|---|---|
autorun=(true, false) | true | 是否自动运行 |
lang=... | none | 拓展支持的语言(PHP,JAVA这些已经能自动识别),详情可以查看文档,如果设置多个:(?lang=css&lang=ml) |
skin=... | none | 设置主题,支持官方主题 |
callback=js_ident | window.exports["js_ident"] will be called when prettyprinting finishes. If specified multiple times, all are called. |
例如:
<script src="https://cdn.jsdelivr.net/gh/google/code-prettify@master/loader/run_prettify.js?lang=css&skin=sunburst"></script>
标识支持css语言,同时引入官方主题-sunburst
手动引入
从管关系下载js和css文件,然后引入:
<link rel="stylesheet" type="text/css" href="prettify.css">
<script type="text/javascript" src="prettify.js"></script>
Prettify 使用还是比较方便的,只需要在 pre、code、xmp 标签上加入 class = "prettyprint" 类即可,如:
<pre class="prettyprint">
source code here
</pre>
如果是Markdown 则:
<?prettify?>
<pre class="prettyprint">
code here
</pre>
官方例子:链接
行号
默认是没有行号的,如需增加,在class后面追加linenums,如:
<pre class="prettyprint linenums">
Many
lines
of
code
</pre>
虽然出现了行号,但是只每隔5行才显示一个,现在不符合国人习惯。修改方法也简单,在html页面里添加样式代码:
<style>li.L0, li.L1, li.L2, li.L3,li.L5, li.L6, li.L7, li.L8{ list-style-type: decimal !important }</style>
如何在已生成的HTML里追加class
这个也不难,可以正则替换,也使用是在HTML里通过js替换:
(注意,这段代码必须是在jquery引入后才能执行)
<script data-render="script">
$(function () {
// 代码高亮
$('pre').addClass('prettyprint linenums').attr('style', 'overflow:auto');
})
</script>