設計表頭固定並且列寬可調整的Table表格

表頭固定

我們都知道HTML中table的thead是會隨着tbody滾動的。所以要實現tbody內容滾動,而表頭固定就需要用兩個table來顯示,一個顯示只用於表頭,另一個用於顯示tbody內容。

表格列寬調整

添加一個圖標或者div,作爲拖動的標尺,當觸發左鍵事件時(綁定mousedown事件),獲取鼠標當前X座標並設置鼠標樣式
$('.table-col-resize').eq(++i).bind('mousedown', {colNum: i}, function(e) {

	var $thDom = $(e.currentTarget).parent('th');

	$scope.originalPos = e.pageX; // 獲取鼠標開始拖動時的座標
	
	// ...
});
鼠標樣式:
cursor: col-resize

拖動時(綁定mousemove事件),通過event獲取座標來更新這個div或圖片left屬性。
<pre name="code" class="javascript">$('body').bind('mousemove', function(e) {
	$('.col-scaleplate').css('left', e.pageX - 8 + 'px');
});


效果如下:
當鬆開鼠標時(綁定mouseup事件),計算鼠標移動距離,並設置指定列的“thead”和“tbody”列寬。
$('body').bind('mouseup', function(e) {

	$('.col-scaleplate').css('left', '-40px'); // 將標尺div移出視線

	$scope.targetPos = e.pageX; // 獲取鼠標按鍵放開時的X座標
	
	jQuery(this).unbind('mousemove').unbind('mouseup'); // 取消body的mousemove和mouseup綁定

	// 計算鼠標移動的距離
	console.log($scope.targetPos - $scope.originalPos); //TODO del
	var distance = $scope.targetPos - $scope.originalPos;

	// 設置兩個table的列寬
	$thDom.width($thDom.width() + distance); // 設置作爲thead的table列寬
	$('tr').each(function() { // 設置作爲tbody的table列寬
		var $tdDom = $(this).find('td').eq($scope.currentColNum).find('>div');
		$tdDom.width($tdDom.width() + distance);
	});

});

完整代碼正在整理中...

整理進度基本完畢,內容如下:
PS:看代碼前我先磨嘰幾句啊!這個是用angular實現的,因爲使用ng-repeat循環創建<tr>比較方便,而且我項目中有恰好安裝了angular包。
<html>
<head>
    <title>table表頭固定以及列寬可調</title>
    <meta charset="utf-8">
    <style>
        th {
            width: 200px;
            border-bottom: 1px solid #ddd;
        }
        td {
            width: 200px;
            border-bottom: 1px solid #ddd;
        }
        .table-col-resize {
            cursor: col-resize;
        }
        .col-div {
            text-overflow: ellipsis !important;
            overflow: hidden;
            white-space: nowrap;
            width: 197px;
        }
        .col-scaleplate {
            position: absolute;
            width: 4px;
            height: 100%;
            background-color: rgb(171, 171, 171);
            top: 0;
            left: -66px;
        }
        .no-select {
            -webkit-user-select: none;  /* Chrome all / Safari all */
            -moz-user-select: none;     /* Firefox all */
            -ms-user-select: none;      /* IE 10+ */
            user-select: none;          /* Likely future */
        }
    </style>
<body ng-app="app" ng-controller="tableController">
<div style="width: 830px; background-color: #f5f5f5; position: relative;" class="first-table">
    <table>
        <tr>
            <th>Col1<span style="float: right;" class="table-col-resize">|</span></th>
            <th>Col2<span style="float: right;" class="table-col-resize">|</span></th>
            <th>Col3<span style="float: right;" class="table-col-resize">|</span></th>
            <th>Col4<span style="float: right;" class="table-col-resize">|</span></th>
        </tr>
    </table>
    <div style="overflow-y: auto;height: 400px; width: 830px;" class="second-table">
        <table>
            <tr ng-repeat="row in datas track by $index">
                <td ng-repeat="unit in row">
                    <div class="col-div">
                        <span>{{unit}}</span>
                    </div>
                </td>
            </tr>
        </table>
    </div>

    <div class="col-scaleplate"></div>
</div>

<script src="../bower_components/angular/angular.js"></script>
<script src="../bower_components/jQuery/dist/jquery.min.js"></script>
<script>
    var myApp = angular.module('app', []).controller('tableController', function($scope) {

        // 清除文本選中狀態
        var clearTxtSelect= "getSelection" in window ? function(){
            window.getSelection().removeAllRanges();
        } : function(){
            document.selection.empty();
        };

        // 構建表格數據
        var words = ['a','b','c','d','e','f','是','啥','將','月','天','明','r','l','e','一','雙','人','將'];
        $scope.datas = [];
        for (var i = 0; i < 20; i++) {
            var row = [];
            for (var j = 0; j < 4; j++) {
                var unit = words[parseInt(Math.random() * words.length)];
                for (var k = 0; k < parseInt(Math.random() * 80); k++) {
                    unit += words[parseInt(Math.random() * words.length)];
                }
                row.push(unit);
            }
            $scope.datas.push(row);
        }

        // 調整列寬
        var i = -1;
        $('th').each(function() {
            $('.table-col-resize').eq(++i).bind('mousedown', {colNum: i}, function(e) {

                var $thDom = $(e.currentTarget).parent('th');

                $scope.originalPos = e.pageX;
                $('.col-scaleplate').css('left', e.pageX - 8 + 'px');

                // 當前第幾列 (從0開始)
                $scope.currentColNum = e.data.colNum;

                // 爲body添加mousemove綁定
                $('body').bind('mousemove', function(e) {
                    clearTxtSelect();
                    $('.col-scaleplate').css('left', e.pageX - 8 + 'px');
                });

                // 爲body添加mouseup綁定
                $('body').bind('mouseup', function(e) {

                    $('.col-scaleplate').css('left', '-40px'); // 將標尺div移出視線

                    $scope.targetPos = e.pageX;
                    // 取消body的mousemove和mouseup綁定
                    jQuery(this).unbind('mousemove').unbind('mouseup');

                    // 計算鼠標移動的距離
                    console.log($scope.targetPos - $scope.originalPos); //TODO del
                    var distance = $scope.targetPos - $scope.originalPos;

                    // 設置兩個table的列寬
                    $thDom.width($thDom.width() + distance);
                    $('tr').each(function() {
                        var $tdDom = $(this).find('td').eq($scope.currentColNum).find('>div');
                        $tdDom.width($tdDom.width() + distance);
                    });

                    // 設置兩個表格的總寬度
                    $('.first-table').width($('.first-table').width() + distance);
                    $('.second-table').width($('.second-table').width() + distance);

                    clearTxtSelect();

                });
            });
        });

    });
</script>
</body>
</html>



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