1. 程式人生 > >前端-表頭固定,內容滾動

前端-表頭固定,內容滾動

原理: 利用兩個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>

效果圖: