使用 prismjs 代码高亮库


#Web 前端开发#


primejs 可以对 html 中pre标识的源代码进行高亮。

官网:https://prismjs.com

如何下载

进入 https://prismjs.com/download.html ,选择主题、要支持的编程语言、插件,然后下载 js 和 css 文件(名称是 prism.js、prism.css)。

在 HTML 中引入 js 和 css 文件即可。

示例1

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="https://cdn.bootcss.com/twitter-bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="assets/prism.css"/>
    <style>
        .container {
            margin-top: 50px;
            background-color: cadetblue;
        }
    </style>
</head>
<body>

<div class="container">
<pre>
<code>12
print 'hi'
print 'hello hello hello hello hello hello hello hello hello hello hello'</code>
</pre>
</div>

<div class="container">
<pre>
<code class="language-python">12
print 'hi'
print 'hello hello hello hello hello hello hello hello hello hello hello'</code>
</pre>
</div>

<script type="text/javascript" src="assets/prism.js" ></script>
</body>
</html>

上面的代码中引入了 bootstrap.css ,它不是必须的,只是用于辅助页面的展示效果。

我们看下代码渲染效果:

第1个 pre 代码块中 code 没有使用language-xxx 作为class,所以prismjs不会去渲染。 第2个 pre 代码块中 code 使用了language-python 作为class,所以prismjs按照Python语法进行了渲染。

示例2

使用 line number 插件显示行号。用法很简单,在pre 或者 code 中加上 line-numbers 即可。

<div class="container">
<pre class="line-numbers language-python">
<code>12
print 'hi'
print 'hello hello hello hello hello hello hello hello hello hello hello'</code>
</pre>
</div>

<div class="container">
<pre class="line-numbers">
<code class="language-python">12
print 'hi'
print 'hello hello hello hello hello hello hello hello hello hello hello'</code>
</pre>
</div>

<div class="container">
<pre class="">
<code class="language-python line-numbers">print 'hi'</code>
</pre>
</div>

效果:

可以看到,language-xxx 也可以加在 pre 的 class 中,但是不推荐。

示例3

在prismjs下载界面选择dark主题,重新下载js和css。

示例:

<div class="container">
<pre>
<code class="language-python">12
print 'hi'
print 'hello hello hello hello hello hello hello hello hello hello hello'</code>
</pre>
</div>

<div class="container">
<pre class="">
<code class="language-python">print 'hi'</code>
</pre>
</div>

效果:

示例4:页面局部刷新后,让高亮重新生效

执行下面的代码即可:

Prism.highlightAll()

( 本文完 )