我试图在我的网页中的源代码旁边显示行号,我使用了两个表列,一个用于行号,另一个用于源代码,我有以下要求:
- 鼠标悬停时在行号前显示一个特殊图标 在它之上
- 特殊图标(下面代码中的“x”)是一个 anchor 标记,我会 像 anchor 扩展到整个td单元格
- 选择源代码时,不要选择和复制行 数
如果我没有要求 3,我可以简单地在 <a>
中显示行号元素并将其扩展到完整的 td。我设法让事情变得可行,我的代码如下:
HTML
<table id='file-table' class='table table-hover table-condensed'>
<tr>
<!--other td-->
<td data-line-number='1'>
<a type='button' role='button' ng-click='doSomething()'>x</a>
</td>
<!--other td-->
</tr>
</table>
CSS
/*the concerning column is the 4th in the table*/
#file-table tr td:nth-child(4) {
width: 4%;
border-right: 1px solid #ddd;
padding: 0px 5px 0px 5px;
}
#file-table tr td:nth-child(4)::after {
content: attr(data-line-number);
padding: 0px 5px 0px 5px;
text-align: right;
display: block;
}
#file-table tr td:nth-child(4) > a {
display: none;
}
#file-table tr td:nth-child(4):hover > a {
width: 100%;
height: 100%;
text-align: left;
display: block;
}
所以想法是使用::after 在 <td>
中显示行号并隐藏 <a>
直到悬停在它上面,当 <a>
将显示并扩展到 100% 宽度。但是,我现在遇到的问题是连行号都显示正常:
当我将鼠标悬停在它上面时,'x' 显示但将 td 分成两行:
我在这里做错了什么?如果可能的话,如何确保“x”显示在同一行?
最佳答案
我不确定您是否需要担心特殊的数据属性,因为使用纯 CSS 和 counter-increment
属性可以实现行号。
让超链接出现在悬停时并且(我假设)覆盖任何其他文本将需要一些绝对定位,但可以通过以下方式实现:
#file-table {
counter-reset: line;
}
#file-table tr:before {
counter-increment: line;
content: counter(line);
display: inline-block;
color: #888;
text-align: center;
padding: 12px 8px;
font-size: 0.5em;
}
#file-table td {
position: relative;
width: 100%;
}
#file-table td a {
display: none;
}
#file-table td:hover a {
position: absolute;
display: block;
width: 100%;
z-index: 2;
top: 0;
background: #eee;
padding: 5px 2px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<table id="file-table" class="table table-hover table-condensed">
<tr><td>Line 1<a type='button' role='button' ng-click='doSomething()'>x</a></td></tr>
<tr><td>Line 2<a type='button' role='button' ng-click='doSomething()'>x</a></td></tr>
<tr><td>Line 3<a type='button' role='button' ng-click='doSomething()'>x</a></td></tr>
<tr><td>Line 4<a type='button' role='button' ng-click='doSomething()'>x</a></td></tr>
<tr><td>Line 5<a type='button' role='button' ng-click='doSomething()'>x</a></td></tr>
<tr><td>Line 6<a type='button' role='button' ng-click='doSomething()'>x</a></td></tr>
<tr><td>Line 7<a type='button' role='button' ng-click='doSomething()'>x</a></td></tr>
</table>
一些注意事项:
Bootstrap 对表格的悬停效果是一个 RGBA 值。为了 实现覆盖 100% 表格单元格的超链接,你必须 实现另一个背景。两者重叠并创建一个 颜色比标准颜色深,因此您可能需要调整一下。
表格单元格需要定义宽度,否则
:before
中的行号往往会导致一些奇怪的位置。
关于javascript - 使用::after 选择器显示行号,但在将鼠标悬停在包含表的 td 单元格上时还会在行号旁边显示一个 <a> 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38880194/