如何轻松地给代码添加行号
为代码添加行号往往是一项繁琐的任务,尤其是在需要显示精美的格式时。对于这种场景,一种简单又方便的方法是使用 CSS 的 ::before 伪元素。
在需要添加行号的
#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 lang="en"> <head> <meta charset="UTF-8"> <title>行号</title> </head> <body> <p>测试页面</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/c1c2c2ed740f" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Java免费学习笔记(深入)</a>”;</p> </body> </html>`.split('\n').forEach((text, index) => { var $line = document.createElement('p'); $line.dataset.lineNumber = index + 1; $line.innerText = text; $code.appendChild($line); });
通过这种方式,您可以轻松地为代码添加行号,并根据需要自定义其外观。
以上就是如何使用 CSS 和 JavaScript 为代码添加行号?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号