table-固定首列

首先,table外层套两层div,outerDiv和 innerDiv

<div class="outerDiv">
	<div class="innerDiv">
			<table border="0" class="table">
					<thead class="thead">
					    <tr>
					           <th class="wd200">名称</th>	
					            <th class="wd150">性别</th>
					            <th class="wd150">班级</th>
					            <th class="wd150">语文</th>
					            	<th class="wd150">数学</th>
					            <th class="wd120">合计</th>
					          </tr>
		      				</thead>
						  	<tbody class="tbody_f">
							      	<tr>
  										<td class="">张三</td>
  										<td class="">男</td>
  										<td class="">2</td>
  										<td class="">80</td>
    									<td class="">90</td>
  										<td class="">170</td>
								</tr>
								<tr>
  										<td class="">李四</td>
  										<td class="">男</td>
  										<td class="">2</td>
  										<td class="">80</td>
    									<td class="">90</td>
  										<td class="">170</td>
								</tr>
						  </tbody>
				</table>
		</div>
</div>

outerDiv和innerDiv的样式设置如下:

.outerDiv{
	position: relative; 
	overflow: hidden;
}
.innerDiv{
	overflow: auto; 
	padding-left: 230px; // padding-left是固定列的宽度
} 

设置table的样式:
注: 第一列position设为absolute

.table{font-size: 12px;  width: 100%;border-spacing:0px; table-layout: fixed;border-bottom:0px; padding: 0px; margin:0px;border-collapse:collapse;font-weight: bold;}
.thead {border-spacing: 0px; }
.thead tr{ height: 38px; line-height: 38px;font-size: 14px;}
.tbody{text-align: center; font-weight: bold; clear: both;border-spacing: 0px;}
.tbody tr td{font-size: 14px;font-weight: bold;padding: 20px 0px; min-height: 30px;vertical-align: top;}
.tbody tr td:nth-child(1),.thead_f th:nth-child(1){text-align: left;padding-left: 30px;}
.table th:first-child, .table td:first-child{position: absolute;left: 0px; width: 200px; border-right: 1px solid #DFE2E6;}

ps: 重要的一点,为了保证固定列高度和其他高度保持一致,需要遍历没一行,判断高度,并设置

$('.table td:first-child').each(function(){
    var td_height = $(this).outerHeight();
    var tr_height = $(this).parent().outerHeight();
    if (td_height > tr_height) {
      $(this).parent().height(td_height);
    } else if (td_height < tr_height) {
      $(this).outerHeight(tr_height);
    }
});

猜你喜欢

转载自blog.csdn.net/weixin_42979149/article/details/88389183