指定した行と、一列目を固定し、コンテンツをスクロールできるテーブル作成。
大量のデータがあるとき(バスの運賃表や時間割など)に使用しやすい大型テーブル用
テーブル作成でなるべくthかtdに偏らせるとよい。幅はすべて同じように固定するので、変則な行、列幅を用意しないこと。
colspanなどで結合は行わないこと。
cssのみでは表現できないので、javascriptも併用する。
【css】
/* テーブル全体枠 */
.outer {
position: relative;
padding-top: 30px;
overflow: hidden;
width: 600px;
}
/* スクロール表示用枠 */
.scroller {
overflow: auto;
background: #f5f5f5;
max-height: 300px;
width: 600px;
}
/*テーブル幅・高さを固定 ※設定しなくてもよい?*/
.box {
/*widthを該当ページ内に記述*/
}
/*header-固定用*/
table thead {
position: absolute;
top: 0;
left: 0;
z-index: 2;
height: 30px;
}
table thead td {
line-height: 100%;
font-size: 11px;
height: 30px;
width: 70px;
}
/*body*/
table tbody {
/*widthを該当ページ内に記述*/
}
table tbody td {
width: 70px;
height: 30px;
}
table th {
border: 1px solid #999;
font-size: 11px;
font-weight: normal;
line-height: 100%;
text-align: center;
height: 30px;
width: 70px;
}
/* 一列目のカラム */
table th:first-child {
display: block;
position: relative;
z-index: 3;
}
table td {
border: 1px solid #999;
font-size: 12px;
text-align: center;
width: 70px;
line-height: 100%;
empty-cells: show;
}
【javascript(jQuery)】
<cript type="text/javascript">
$(function(){
/* phpを利用して、td、thを吐き出すとき、同時にカラム数分のwidthを計算し、table直前div、thead、tbodyにwidthを設定する場合 */
$(".box").css("width", "px");
//$("table").css("width", "px"); // 必要ない?
$("table thead").css("width", "px");
$("table tbody").css("width", "px");
var scroller = document.getElementById("scroller");
var thead, theadF, tbodyF;
thead = $("table thead");
theadF = $("table thead tr th:first-child");
tbodyF = $("table tr th:first-child");
$('.scroller').scroll(function () {
var left= $(this).scrollLeft(); //scrollerのスクロール位置
$("table thead").css("left", left * -1); //thead scroll
//$("table tfoot").css("left", left * -1); //tfoot scroll
thead.css("left", left * -1);
theadF.css("left", left);
tbodyF.css("left", left);
});
})
</script>
【html】
<div class="outer"> <div class="scroller"> <div class="box"> <table> <thead> <tr> <th>×</th><th>1</th>....<th>60</th> </tr> </thead> <tbody> <tr> <th>○○</th><td>●●</td>....<td>●●</td> </tr> . . . <tr> <th>○○</th><td>●●</td>....<td>●●</td> </tr> </tbody> </table> </div> </div> </div>