highlight.js网页代码高亮插件左侧怎么展示行号

前言

前几天分享了一篇网页代码高亮插件highlight.js,效果还不错,因为highlight.js本身没有行号展示,对于观感和体验上来源还是有点不太友好哈,恩。。。这几天越看越难受,忍不了还是弄一下吧

原文地址:https://www.ngxcode.com/archives/282.html

line_number.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));

line_number.css

.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);
}

代码引用

<link rel="stylesheet" href="/wp-includes/highlight/line_number.css">
<script src="/wp-includes/highlight/line_number.js"></script>
<script>
hljsln.initLineNumbersOnLoad();
</script>

OK! 操作完成,上面代码框展示的就是配置后的效果了,因为我不大喜欢侧那块灰色的条,所以在css里面注释了,因人而异吧,喜欢的可以自己打开试下效果

highlight.js 代码高亮展示左侧行号

posted @ 2023-05-13 00:19  wangnbx  阅读(151)  评论(0编辑  收藏  举报