如何在代码块Code中添加行号

444 阅读1分钟

实现原理,把\n替换为 li

完整代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>如何在源代码块中添加行号</title>
    <style>
    .line-code-list {
        list-style: none;
    }
    .line-code-item {
        counter-increment: line_num 1;
        border-bottom: 1px dashed #eee;
    }
    .line-code-item::before {
        content: counter(line_num) ".";
        display: inline-block;
        text-align: right;
        width: 40px;
        padding-right: 4px;
    }
    </style>
</head>
<body>

<pre>
    <code id="code"></code>
</pre>

<script>
    const code = '第一行xxx\n第二行xxx\n第三行xxx\n第四行xxx'
    let newCode = '<ul class="line-code-list"><li class="line-code-item">'
        newCode += code.replace(/\n/g, '\n</li><li class="line-code-item">')
        newCode += '</li></ol>'
        
    document.querySelector('#code').innerHTML = newCode
</script>
</body>
</html>

Tips:也可以直接使用有序列表 <ol><li></li></ol>,不过样式不能自定义