CSS代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
.hljsln {
position: relative;
display: block;
padding-left: 3em !important;
}

.hljsln .ln-bg {
position: absolute;
z-index: 1;
top: 0;
left: 0;
width: 2.2em;
height: 100%;
border-right: 1px solid #555;
background: rgba(255, 255, 255, 0.18);
}

.hljsln .ln-num {
position: relative;
display: inline-block;
height: 1em;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}

.hljsln .ln-num::before {
position: absolute;
z-index: 2;
top: 0;
right: 0;
margin-right: 1em;
color: #777;
font-style: normal;
font-weight: normal;
content: attr(data-num);
}

JavaScript代码

将JavaScript代码保存为文件 highlight.line-numbers.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
(function (w, d) {
w.hljsln = {
initLineNumbersOnLoad: initLineNumbersOnLoad,
addLineNumbersForCode: addLineNumbersForCode
};

function initLineNumbersOnLoad() {
if (d.readyState === 'interactive' || d.readyState === 'complete') {
documentReady();
} else {
w.addEventListener('DOMContentLoaded', function () {
documentReady();
});
}
}

function addLineNumbersForCode(html) {
var num = 1;
html = '<span class="ln-num" data-num="' + num + '"></span>' + html;
html = html.replace(/\r\n|\r|\n/g, function (a) {
num++;
return a + '<span class="ln-num" data-num="' + num + '"></span>';
});
html = '<span class="ln-bg"></span>' + html;
return html;
}

function documentReady() {
var elements = d.querySelectorAll('pre code');
for (var i = 0; i < elements.length; i++) {
if (elements[i].className.indexOf('hljsln') == -1) {
var html = elements[i].innerHTML;
html = addLineNumbersForCode(html);
elements[i].innerHTML = html;
elements[i].className += ' hljsln';
}
}
}
}(window, document));

加载并执行初始化如下

1
2
3
4
<link rel="stylesheet"  href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/styles/androidstudio.min.css">
<script th:src="@{/static/js/highlight.line-numbers.js}"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();hljsln.initLineNumbersOnLoad();</script>

结果如下图

img

可以看到第1和8行是空行,但是也显示了行号,为了让它不显示,将上面JavaScript代码中的addLineNumbersForCode方法修改成下面的代码即可:(修改后结果如下图所示)

JavaScript代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function addLineNumbersForCode(html) {
var num = 0;
var max = 0;
html = html.replace(/\r\n|\r|\n/g, function (b) {
max++;
if (max != 0) {
return b;
}
});
html = html.replace(/\r\n|\r|\n/g, function (a) {
num++;
if (num != 0 && num != max) {
return a + '<span class="ln-num" data-num="' + num + '"></span>';
}else if (num != 0 && num == max) {
return a + ' ';
}
});
html = '<span class="ln-bg" style="margin-left: 1px"></span>' + html;
return html;
}

图片:

img

PS.

来源:自己写 highlight.js 行号插件 | 天角星