原理: 利用两个table,一个div包装一个table表头,一个div包装一个table的body
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="js/jquery-3.2.1.js" ></script>
<script type="text/javascript" src="asset/bootstrap-3.3.5-dist/js/bootstrap.min.js" ></script>
<link rel="stylesheet" href="asset/bootstrap-3.3.5-dist/css/bootstrap.min.css" />
<style>
#div-table-wrapper {
width: 500px;
margin-top: 50px;
margin-left: 200px;
margin-bottom: 100px;
}
.table-head-wrapper {
/*//设置第一个table-wrapper中height,不然overflow-y:auto;不起作用*/
height: 50px;
width: 100%;
}
.table-body-wrapper {
margin-top: -11px;
/*//设置第二个table-wrapperheight*/
height: 200px;
/*//设置垂直滚动条*/
overflow-y: auto;
overflow-x: hidden;
border-bottom: 1px solid #ddd;
border-left: 1px solid #ddd;
border-right: 1px solid #ddd;
}
#btn-wrapper {
margin-left: 200px;
margin-top: -85px;
}
</style>
<script type="text/javascript">
$(function(){
$("#btn-add").click(function(){
$("#tbody-content").append("<tr><td>小贝</td><td>23</td></tr>");
var $tableHeadWrapper = $(".table-head-wrapper");
var $tableBodyWrapper = $(".table-body-wrapper");
var $tableBody = $("#table-body");
//获取第二个table设置的高度
var tableBodyWrapperHeight = $tableBodyWrapper.height();
//table的实际高度(里面有动态数据,高度随着数据添加而)
var tableBodyHeight = $tableBody.height();
if(tableBodyHeight >= tableBodyWrapperHeight){
$tableHeadWrapper.css({"overflow-y": "auto"});
}else{
$tableHeadWrapper.css({"overflow-y":"hidden"});
}
})
});
</script>
</head>
<body>
<div id="div-table-wrapper">
<div class="table-head-wrapper" >
<table class="table table-bordered">
<colgroup>
<col width="50%" />
<col width="50%" />
</colgroup>
<thead>
<tr>
<td>姓名</td>
<td>年龄</td>
</tr>
</thead>
</table>
</div>
<div class="table-body-wrapper">
<table class="table table-bordered" id="table-body" >
<colgroup>
<col width="50%" />
<col width="50%" />
</colgroup>
<tbody id="tbody-content">
<tr><td>小贝</td><td>23</td></tr>
<tr><td>小贝</td><td>23</td></tr>
</tbody>
</table>
</div>
</div>
<div id="btn-wrapper">
<input id="btn-add" type="button" class="btn btn-primary" value="增加一行" />
</div>
</body>
</html>
效果图: