将鼠标悬停在 pre - 如何使用纯 CSS 突出显示单行?
Hover over a pre - how to highlight a single line with plain CSS?
我有一些<pre>
块。
是否可以仅使用 CSS,在将鼠标悬停在单行上时突出显示单行?
==更新==
下面是一些示例代码:
<pre>
#include <stdio.h>
int main()
{
printf("Hello World");
return 0;
}
</pre>
当行变长时,悬停时突出显示它们会很有用。
无法通过 PHP 读取源文件,或者我会将其拆分为单独的 <pre>
行,并使用琐碎的 pre:hover
CSS。
pre:nth-child
不是解决方案,因为代码行不是 CSS 意义上的 "children"。
pre:first-line
有效,但当然只适用于第一行。
==更新二==
由于 CSS 似乎仅限于 first-line
,感谢 Zeke 的建议,我找到了一个几乎简单的方法来获得我想要的东西。
HTML:
<pre id="raw">
#include <stdio.h>
int main()
{
printf("Hello World");
return 0;
}
</pre>
<!-- 1×1 transparent PNG for the onload -->
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP4/x8AAwAB/2+Bq7YAAAAASUVORK5CYII=" onload="PreHover()" />
CSS:
#pre div:hover {
background: #ff0;
}
原版 Javascript:
function PreHover() {
var output = '';
var preBox = document.getElementById('raw');
var txt = preBox.innerHTML.split('\n');
for(var x=0;x<txt.length-1;x++) {
output = output + '<div>'+txt[x]+'</div>';
}
preBox.innerHTML = output;
}
This will help you wrap div for each line
var txt = $('pre').html().split("\n");
var output = "";
for(var x=0;x<txt.length-1;x++)
output = output + "<div>"+txt[x]+"</div>";
}
$('pre').html(output);
You can write one line css then for highlighting:
pre div:hover { background-color: rgba(0,0,0,0.2); }
注意:这需要jQuery
可选:添加white-space:nowrap
以防止换行
Why do this?
因为如果只有 <pre>
,它将是一个 DOM 元素,其中仅包含 text ,您可以对其进行整体更改,而不是逐行更改。
要更好地控制每一行,通过使用 操纵 <pre>
中包含的文本来构建新的 DOM 元素pre 包含许多 div,每个包含一行文本。现在您可以掌握每个 div
我有一些<pre>
块。
是否可以仅使用 CSS,在将鼠标悬停在单行上时突出显示单行?
==更新==
下面是一些示例代码:
<pre>
#include <stdio.h>
int main()
{
printf("Hello World");
return 0;
}
</pre>
当行变长时,悬停时突出显示它们会很有用。
无法通过 PHP 读取源文件,或者我会将其拆分为单独的 <pre>
行,并使用琐碎的 pre:hover
CSS。
pre:nth-child
不是解决方案,因为代码行不是 CSS 意义上的 "children"。
pre:first-line
有效,但当然只适用于第一行。
==更新二==
由于 CSS 似乎仅限于 first-line
,感谢 Zeke 的建议,我找到了一个几乎简单的方法来获得我想要的东西。
HTML:
<pre id="raw">
#include <stdio.h>
int main()
{
printf("Hello World");
return 0;
}
</pre>
<!-- 1×1 transparent PNG for the onload -->
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP4/x8AAwAB/2+Bq7YAAAAASUVORK5CYII=" onload="PreHover()" />
CSS:
#pre div:hover {
background: #ff0;
}
原版 Javascript:
function PreHover() {
var output = '';
var preBox = document.getElementById('raw');
var txt = preBox.innerHTML.split('\n');
for(var x=0;x<txt.length-1;x++) {
output = output + '<div>'+txt[x]+'</div>';
}
preBox.innerHTML = output;
}
This will help you wrap div for each line
var txt = $('pre').html().split("\n");
var output = "";
for(var x=0;x<txt.length-1;x++)
output = output + "<div>"+txt[x]+"</div>";
}
$('pre').html(output);
You can write one line css then for highlighting:
pre div:hover { background-color: rgba(0,0,0,0.2); }
注意:这需要jQuery
可选:添加white-space:nowrap
以防止换行
Why do this?
因为如果只有 <pre>
,它将是一个 DOM 元素,其中仅包含 text ,您可以对其进行整体更改,而不是逐行更改。
要更好地控制每一行,通过使用 操纵 <pre>
中包含的文本来构建新的 DOM 元素pre 包含许多 div,每个包含一行文本。现在您可以掌握每个 div