JavaScript表格頭部拉伸

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		#carTable{width:100%;}
		td{text-align:center;}
	</style>
</head>
<body>
	<table id="carTable" border="1" cellspacing="0" cellpadding="0">
		<thead>
			<tr>
				<th>header</th>
				<th>header</th>
				<th>header</th>
				<th>header</th>
				<th>header</th>
			</tr>
		</thead>
		<tbody>
			<tr>
				<td>data</td>
				<td>data</td>
				<td>data</td>
				<td>data</td>
				<td>data</td>
			</tr>
		</tbody>
	</table>
	<script>
		var tTD; //用來存儲當前更改寬度的Table Cell,避免快速移動鼠標的問題
		var table = document.getElementById("carTable");
		for (j = 0; j < table.rows[0].cells.length; j++) {
		    table.rows[0].cells[j].onmousedown = function() {
		        //記錄單元格
		        tTD = this;
		        if (event.offsetX > tTD.offsetWidth - 10) {
		            tTD.mouseDown = true;
		            tTD.oldX = event.x;
		            tTD.oldWidth = tTD.offsetWidth;
		        }
		        //記錄Table寬度
		        //table = tTD; while (table.tagName != ‘TABLE') table = table.parentElement;
		        //tTD.tableWidth = table.offsetWidth;
		    };
		    table.rows[0].cells[j].onmouseup = function() {
		        //結束寬度調整
		        if (tTD == undefined) tTD = this;
		        tTD.mouseDown = false;
		        tTD.style.cursor = 'default';
		    };
		    table.rows[0].cells[j].onmousemove = function() {
		        //更改鼠標樣式
		        if (event.offsetX > this.offsetWidth - 10)
		            this.style.cursor = 'col-resize';
		        else
		            this.style.cursor = 'default';
		        //取出暫存的Table Cell
		        if (tTD == undefined) tTD = this;
		        //調整寬度
		        if (tTD.mouseDown != null && tTD.mouseDown == true) {
		            tTD.style.cursor = 'default';
		            if (tTD.oldWidth + (event.x - tTD.oldX) > 0)
		                tTD.width = tTD.oldWidth + (event.x - tTD.oldX);
		            //調整列寬
		            tTD.style.width = tTD.width;
		            tTD.style.cursor = 'col-resize';
		            //調整該列中的每個Cell
		            table = tTD;
		            while (table.tagName != 'TABLE') table = table.parentElement;
		            for (j = 0; j < table.rows.length; j++) {
		                table.rows[j].cells[tTD.cellIndex].width = tTD.width;
		            }
		            //調整整個表
		            //table.width = tTD.tableWidth + (tTD.offsetWidth – tTD.oldWidth);
		            //table.style.width = table.width;
		        }
		    };
		}
	</script>
</body>
</html>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章