在CSS中,突出显示表格的行非常简单。 tr:hover { background: yellow; }
tr:hover { background: yellow; }
在那里做得很好。 但是突出显示列一直比较棘手,因为没有单个HTML元素是列中表格单元格的父元素。 少量JavaScript可以轻松处理它,但是Andrew Howe最近通过电子邮件给我分享了他在StackOverflow上发现的一些小技巧,该技巧由Matt Walton发布。
那是几年了,所以我想我要把它清理干净并张贴在这里。
诀窍是在<td>上使用巨大的伪元素,这些伪元素被表溢出隐藏
您真的不知道CSS的表格有多大,因此只需使伪元素超高,负上限值为一半即可。
table {
overflow: hidden;
}
tr:hover {
background-color: #ffa;
}
td, th {
position: relative;
}
td:hover::after,
th:hover::after {
content: "";
position: absolute;
background-color: #ffa;
left: 0;
top: -5000px;
height: 10000px;
width: 100%;
z-index: -1;
}
负的z-index
将其保持在内容之下。 负z-index
是一个有趣的技巧,但是请注意,此表不能嵌套在其他有背景的元素中,否则突出显示将在它们下面。
您可以在这里看到实际效果:
见笔行和列CSS高亮只由克里斯Coyier( @chriscoyier上) CodePen 。
触摸即可工作
悬停伪类仅在触摸设备上起作用。 首先,该元素需要可聚焦,默认情况下哪些表单元格不是。 您当然可以在表单元格中添加一个click事件处理程序,并只需执行JavaScript中的所有操作,但这是一种将大部分工作保留在CSS中的方法:
// Whatever kind of mobile test you wanna do.
if (screen.width < 500) {
// :hover will trigger also once the cells are focusable
// you can use this class to separate things
$("body").addClass("nohover");
// Make all the cells focusable
$("td, th")
.attr("tabindex", "1")
// When they are tapped, focus them
.on("touchstart", function() {
$(this).focus();
});
}
然后在CSS中也添加:focus样式。
td:focus::after,
th:focus::after {
content: '';
background-color: lightblue;
position: absolute;
left: 0;
height: 10000px;
top: -5000px;
width: 100%;
z-index: -1;
}
td:focus::before {
background-color: lightblue;
content: '';
height: 100%;
top: 0;
left: -5000px;
position: absolute;
width: 10000px;
z-index: -1;
}
在我的最后一个演示中,我对CSS选择器有些幻想,以确保空表单元格不会触发任何内容, <thead>
中的表头仅选中列,而<tbody>
中的表头仅选中行。
您可以在最终演示中看到这一点。 和这里的触摸工作:
翻译自: https://css-tricks.com/simple-css-row-column-highlighting/