我正在尝试以 html+css(无 JavaScript)呈现源代码,以便:
- 它使用行号进行渲染。
- 选择代码时不会复制行号。
- 保留内部空格/制表符/换行符。
- 行号是自动生成的。
我得到的解决方案使用 CSS 计数器和一个表,其中最左边的列是 data-psuedo-content(也标记为不可选择)。它可以在 Firefox、Safari 和 Chrome 中正确呈现,但将文本复制到剪贴板时出现问题。
- 在 Chrome 和 Safari 中,复制到剪贴板的文本与源文本匹配。
- 在 Firefox 中,剪贴板中的行是双倍行距:每行之间有额外的空白行。
有一个演示on jsfiddle这说明了问题所在。尝试将文本复制到 Firefox 中的剪贴板会在每行之间放置一个空行(即额外的换行符)。
如何解决这个问题(仅使用 html+css)?
.code {
background-color: none;
border: none;
padding: 0;
}
pre.code {
line-height: 1.6;
white-space: pre-wrap;
width: 100%;
margin: 0 auto;
font-size: 14px;
}
;
pre.code table {
counter-reset: linenum;
}
pre.code td.lnum:before {
content: attr(data-psuedo-content) counter(linenum);
}
pre.code td.content {
font-size: 14px;
background: #333740;
color: #ffffff;
white-space: pre-wrap;
padding: 3px;
border-right: solid 2px black;
}
td.lnum {
background-color: #a7a8aa;
color: #000000;
border-right: 2px solid black;
border-top: 1px solid black;
border-bottom: 1px solid black;
border-left: none;
font-size: 12px;
}
pre.code tr {
counter-increment: linenum;
}
.lnum {
-moz-user-select: none;
webkit-user-select: none;
ms-user-select: none;
}
<pre class="code">
<table style="width: 100%;border-collapse: collapse">
<tr><td class="lnum"></td><td class="content">#include <stdint.h></td></tr>
<tr><td class="lnum"></td><td class="content">#include <stdbool.h></td></tr>
<tr><td class="lnum"></td><td class="content"></td></tr>
<tr><td class="lnum"></td><td class="content">/*-</td></tr>
<tr><td class="lnum"></td><td class="content"> | Support for x86 operations that are not exposed natively in C. Each of these</td></tr>
<tr><td class="lnum"></td><td class="content"> | is a fragment of inline-assembly (a way of injecting assembly code into the</td></tr>
<tr><td class="lnum"></td><td class="content"> | compiled program). Each one is wrapped in an inline procedure so that the </td></tr>
</table>
</pre>
最佳答案
不要添加此代码
.lnum {
-moz-user-select: none;
webkit-user-select: none;
ms-user-select: none;
}
关于html - 如何避免 Firefox 从表中复制时出现额外的换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51170894/