如何最方便地给代码加行号?

一段简单的代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>行号</title>
</head>
<body>
    <p>测试页面</p>
</body>
</html>

我想给它加行号,形成下面的形式

使用xmp标签是最简单的做法:
css 部分

    div {
      counter-reset: myCounter;
    }
    xmp::before {
      counter-increment: myCounter 1;
      content: counter(myCounter) '.';
    }

html部分

<div>
<xmp><!DOCTYPE html></xmp>
<xmp><html lang="en"></xmp>
<xmp><head></xmp>
<xmp>    <meta charset="UTF-8"></xmp>
<xmp>    <title>行号</title></xmp>
<xmp></head></xmp>
<xmp><body></xmp>
<xmp>    <p>测试页面</p></xmp>
<xmp></body></xmp>
<xmp></html></xmp>
</div>

xmp不是废弃了吗,我就改用pre,这下麻烦了html部分需要将<>分别转义成

&lt;
&gt;

下面的形式

<div>
<pre>&lt;!DOCTYPE html&gt;</pre>
<pre>&lt;html lang="en"&gt;</pre>
<pre>&lt;head&gt;</pre>
<pre>    &lt;meta charset="UTF-8"&gt;</pre>
<pre>    &lt;title&gt;行号</title></pre>
<pre>&lt;/head&gt;</pre>
<pre>&lt;body&gt;</pre>
<pre>    &lt;p&gt;测试页面</p></pre>
<pre>&lt;/body&gt;</pre>
<pre>&lt;/html&gt;</pre>
</div>

好麻烦,有无简单的js方案来做?

回复
阅读 1k
4 个回答
<div id="code" style="font-size:12px"></div>
<style>
  * {margin: 0; padding: 0;}
  #code p::before {content: attr(data-line-number);min-width: 50px;text-align: right;display: inline-block;padding: 0 5px;color: #ccc;}
</style>
<script>
  var $code = document.getElementById('code');
  `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>行号</title>
</head>
<body>
    <p>测试页面</p>
</body>
</html>`.split('\n').forEach((text, index) => {
    var $line = document.createElement('p');
    $line.dataset.lineNumber = index + 1;
    $line.innerText = text;
    $code.appendChild($line);
  });
</script>

请问您这样的需要是要实现什么需求?您可以了解一下highlightjs插件。应该解决你的问题

你可以参考这篇文章https://blog.csdn.net/qq_41293573/article/details/109045777
const string = `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>行号</title>
</head>
<body>
    <p>测试页面</p>
</body>
</html>
`
const result = string.split('\n').map((item,index)=> `${index+1} ${item}`).join('\n')

可以试一下这个方式,纯 CSS 方案

.code {
    position: relative;
    overflow: hidden;
}
.code::before {
    content: '01.\A 02.\A 03.\A 04.\A 05.\A 06.\A 07.\A 08.\A 09.\A 10.\A 11.\A 12.\A 13.\A 14.\A 15.\A 16.\A 17.\A 18.\A 19.\A 20.\A 21.\A 22.\A 23.\A 24.\A 25.\A 26.\A 27.\A 28.\A 29.\A 30.\A 31.\A 32.\A 33.\A 34.\A 35.\A 36.\A 37.\A 38.\A 39.\A 40.\A 41.\A 42.\A 43.\A 44.\A 45.\A 46.\A 47.\A 48.\A 49.\A 50.\A 51.\A 52.\A 53.\A 54.\A 55.\A 56.\A 57.\A 58.\A 59.\A 60.\A 61.\A 62.\A 63.\A 64.\A 65.\A 66.\A 67.\A 68.\A 69.\A 70.\A 71.\A 72.\A 73.\A 74.\A 75.\A 76.\A 77.\A 78.\A 79.\A 80.\A 81.\A 82.\A 83.\A 84.\A 85.\A 86.\A 87.\A 88.\A 89.\A 90.\A 91.\A 92.\A 93.\A 94.\A 95.\A 96.\A 97.\A 98.\A 99';
    position: absolute;
}

原文链接:https://www.zhangxinxu.com/wo...

推荐问题
宣传栏