将溢出:隐藏在表中更改为悬停时可见

  • 本文关键字:悬停 溢出 隐藏 html css
  • 更新时间 :
  • 英文 :


我有以下HTML表:

table th {
border: 1px solid black;
z-index: 1;
}
.a {
max-width: 100px;
overflow: hidden;
white-space: nowrap;
background: white;
}
.b {
white-space: nowrap;
}
.a:hover {
overflow: visible;
z-index: 2;
}
.c {
background: green;
}
<table>
<tr>
<th class=a><span class=c>a very long text that overflows</span></th>
<th class=b>some other text that is very long and should only be partly obscured</th>
</tr>
</table>

我想要完成的是字段 a 中的文本("溢出的很长的文本"(在悬停时变得可见。表结构不应更改。 事实上,它变得可见,但应该在它后面的文本(来自字段 b(部分掩盖了它。添加的跨度和 z 索引也没有影响。(在Firefox和Chrome中测试(

我想要的是字段 a 中的文本变得可见,并根据需要遮挡字段 b 的尽可能多的内容。

在JSFiddle中也可用:https://jsfiddle.net/tdn15kh8/7/

position: relative;添加到包含溢出文本的th

table th {
border: 1px solid black;
z-index: 1;
}
.a {
max-width: 100px;
overflow: hidden;
white-space: nowrap;
background: white;
position: relative;
}
.b {
white-space: nowrap;
}
.a:hover {
overflow: visible;
z-index: 2;
}
.c {
background: lightgreen;
padding-right: .5rem;
}
<table>
<tr>
<th class=a><span class=c>a very long text that overflows</span></th>
<th class=b>some other text that is very long and should only be partly obscured</th>
</tr>
</table>

查看这篇 MDN 文章以了解堆叠上下文。

要使z-index工作,它也需要一个position

.a:hover {
overflow: visible;
position: relative;
z-index: 2;
}

小提琴示例在这里

position: relative添加到.a中。z指数需要位置:相对或绝对。

还有数据属性解决方案,可让您将文本从数据属性传递到 ::after 伪类。它看起来像这样:

table{width: 300px;}
table th{border: 1px solid black;z-index: 1;}
.a{max-width: 100px;overflow: hidden;white-space: nowrap;background: white;}
.b{white-space: nowrap;}
.c{position: relative;}
.a:hover{overflow: visible;}
.a:hover .c::after{content:attr(data-text); display: block;position: absolute; top: 0; left: 0; background: green;}
<table>
<tr>
<th class="a">
<span class="c" data-text="a very long text that overflows">a very long text that overflows</span>
</th>
<th class="b">some other text</th>
</tr>
</table>

最新更新