你可以只用 CSS(没有 Javascript)来做你原来的十字准线想法。使用::before
和::after
伪元素突出显示。使用这种方法的 Firefox 有一个小问题,所以我为它写了一个修复程序。
border-collapse: collapse
使边界<tds>
以奇怪的方式表现。相反,将边框放在<trs>
and上<cols>
。border-collapse: collapse
也切断边缘。为了解决这个问题,您必须发挥创造力并在所有外部<tds>
和<ths>
. 更奇怪的是,它“吃掉”了顶部的一个像素和底部的两个像素。因此,您需要3px
在顶部获得2px
边框,4px
在底部获得2px
边框。
演示:
CSS:
table {
border-collapse: collapse;
overflow: hidden;
z-index: 1;
}
td, th, .row, .col, .ff-fix {
cursor: pointer;
padding: 10px;
position: relative;
}
tr:last-child td {
border-bottom: 4px solid black;
}
tr, col {
border: 2px solid black;
}
th {
border-top: 3px solid black;
}
th:last-child, td:nth-child(3n) {
border-right: 4px solid black;
}
td:first-child, th:first-child {
border-left: 3px solid black;
}
td:hover {
border: 2px solid red;
}
td:hover:first-child {
border-left: 3px solid red;
}
td:hover:nth-child(3n) {
border-right: 4px solid red;
}
tr:last-child td:hover {
border-bottom: 4px solid red;
}
td:hover::before,
.row:hover::before,
.ff-fix:hover::before {
background-color: #ffa;
content: '\00a0';
height: 100%;
left: -5000px;
position: absolute;
top: 0;
width: 10000px;
z-index: -1;
}
td:hover::after,
.col:hover::after,
.ff-fix:hover::after {
background-color: #ffa;
content: '\00a0';
height: 10000px;
left: 0;
position: absolute;
top: -5000px;
width: 100%;
z-index: -1;
}
HTML:
<table>
<col /><col /><col />
<tr>
<th class="col">First Name</th>
<th class="col">Middle Name</th>
<th class="col">Last Name</th>
</tr>
<tr>
<td>Peter</td>
<td>Jeffery</td>
<td>Griffin</td>
</tr>
<tr>
<td>Lois</td>
<td>Marie</td>
<td>Griffin</td>
</tr>
<tr>
<td>Margie</td>
<td>Ann</td>
<td>Thatcher</td>
</tr>
</table>
脚本:
function firefoxFix() {
if ( /firefox/.test( window.navigator.userAgent.toLowerCase() ) ) {
var tds = document.getElementsByTagName( 'td' ),
ths = document.getElementsByTagName( 'th' );
for( var index = 0; index < tds.length; index++ ) {
tds[index].innerHTML = '<div class="ff-fix">' + tds[index].innerHTML + '</div>';
};
for( var index = 0; index < ths.length; index++ ) {
ths[index].innerHTML =
'<div class="' + ths[index].className + '">'
+ ths[index].innerHTML
+ '</div>';
ths[index].className = '';
};
var style = '<style>'
+ 'td, th { padding: 0 !important; }'
+ 'td:hover::before, td:hover::after { background-color: transparent !important; }'
+ '</style>';
document.head.insertAdjacentHTML( 'beforeEnd', style );
};
};
firefoxFix();