在网页开发过程中,经常会用到代码的展示,而不同颜色的代码,而用highlight.js可以给他加上行号,可以让页面看起来更直观,也更美观。
1、复制以下代码,新建文件,存为highlightjs-line-numbers.js
// 富文本highlightjs-line-numbers.js显示行号 (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));
2、引入文件
<script src="highlightjs-line-numbers.js"></script>
3、实例化使用
// 富文本行号实例化 hljsln.initLineNumbersOnLoad();
文章评论(0)