css实现鼠标移入table时出现滚动条且table内容不移位

一般是这样: 表格的标题和内容分别由一个table组成,其中表格内容的table由一个class=”table-body”的div包裹.css如下

.tContainer .table-body{height:134px;overflow:hidden;}
.tContainer .table-body:hover{overflow-y:auto;}

效果如下:

.tContainer { 500px }
.tContainer table { 100% }
.tContainer th:nth-child(0n+1), .tContainer td:nth-child(0n+1) { 30% }
.tContainer th:nth-child(0n+2), .tContainer td:nth-child(0n+2) { 60% }
.tContainer tr:nth-child(2n) { background: rgba(204, 204, 204, 1) }
.tContainer .table-body { height: 134px; overflow: hidden; border-bottom: 1px solid rgba(204, 204, 204, 1) }
.tContainer .table-body:hover { overflow-y: auto }

index ticker
Citi Commodities Pre-Roll GSCI F0 CVICG0ER
Citi Commodities Pre-Roll GSCI F0 CVICG0ER
Citi Commodities Pre-Roll GSCI F0 CVICG0ER
Citi Commodities Pre-Roll GSCI F0 CVICG0ER
Citi Commodities Pre-Roll GSCI F0 CVICG0ER

缺点很明显,由于滚动条的宽度也占用了一部分表格宽度,鼠标移入时表格内容向左偏移了。

改进的方法,效果如下:

.tContainer .table-body2 td:first-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max- 0 }
.tContainer .table-body2 { height: 100px; overflow: hidden; border-bottom: 1px solid rgba(204, 204, 204, 1) }
.tContainer .table-body2:hover { overflow-y: auto }
.tContainer .table-body2 td:last-child { padding-right: 17px }
.tContainer .table-body2:hover { margin-left: -17px }
.tContainer .table-body2:hover table { margin-left: 17px }

index ticker
Citi Commodities Pre-Roll GSCI F0 CVICG0ER
Citi Commodities Pre-Roll GSCI F0 CVICG0ER
Citi Commodities Pre-Roll GSCI F0 CVICG0ER
Citi Commodities Pre-Roll GSCI F0 CVICG0ER
Citi Commodities Pre-Roll GSCI F0 CVICG0ER

 css code:

.tContainer .table-body2{height:100px;overflow:hidden;}
.tContainer .table-body2:hover{overflow-y:auto;}
.tContainer .table-body2 td:last-child{padding-right:17px;}
.tContainer .table-body2:hover{margin-left:-17px;}
.tContainer .table-body2:hover table{margin-left:17px;}

其中17px代表滚动条的宽度。解决方法是:hover之前通过td:last-child的padding-right预留出滚动条的宽度,hover时通过margin-left:-17px;增加table由于滚动条出现导致的额外宽度,这样table各列的宽度就不会因为出现滚动条而变小了,最后通过table的margin-left:17px;把table位置归位,就不会出现因为滚动条导致table内容左移的现象了。

补充:table column的text-overflow: ellipsis;

一般文字内容放不下时,希望出现…的css code:

overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;

对于table column的css code:

overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max- 0;

Published by

风君子

独自遨游何稽首 揭天掀地慰生平

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注