
如何给代码添加行号?
最简单的做法:使用 xmp 标签
使用 xmp 标签是一种给代码添加行号的简便方法,但要注意该标签已不再使用。
转换为 pre 标签
要使用 pre 标签代替 xmp,需要对 HTML 代码进行转义,如下所示:
<div> <pre><!DOCTYPE html></pre> <pre><html lang="en"></pre> <pre><head></pre> <pre> <meta charset="UTF-8"></pre> <pre> <title>行号</title></pre> <pre></head></pre> <pre><body></pre> <pre> <p>测试页面</p></pre> <pre></body></pre> <pre></html></pre> </div>
简洁的 JavaScript 解决方案
还有一种使用 JavaScript 的更简洁的方法:
<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>以上就是如何给代码添加行号?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号