
如何轻松地给代码添加行号
为代码添加行号往往是一项繁琐的任务,尤其是在需要显示精美的格式时。对于这种场景,一种简单又方便的方法是使用 CSS 的 ::before 伪元素。
在需要添加行号的
元素中,添加以下 CSS 样式:
#code p::before {
content: attr(data-line-number);
min-width: 50px;
text-align: right;
display: inline-block;
padding: 0 5px;
color: #ccc;
}接下来,使用 JavaScript 遍历代码并为每行添加一个
元素:
var $code = document.getElementById('code');
`<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>行号</title>
</head>
<body>
<p>测试页面</p><p><span>筱风工具</span>“<a href="http://tool.fzwqq.com" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Java免费学习笔记(深入)</a>”;</p>
</body>
</html>`.split('
').forEach((text, index) => {
var $line = document.createElement('p');
$line.dataset.lineNumber = index + 1;
$line.innerText = text;
$code.appendChild($line);
});通过这种方式,您可以轻松地为代码添加行号,并根据需要自定义其外观。




还木有评论哦,快来抢沙发吧~