仅CSS的简单行和列突出显示

在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/

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值