etsuxのブログ

自分がハマったことなどを記録しています。

tableのヘッダ固定+縦横スクロールでのセルの幅/高さ揃え

tableのヘッダ固定+縦横スクロールはいろいろなものが公開されているが、やっぱり自作もしてみる。

よくあるtaleを4つ用意してそれぞれをdivで囲み、右下のペインのスクロールバーで右上、左下が同期して動作する。

他と少し違うのは、FourPanesTable-fix-height、FourPanesTable-fix-width、FourPanesTable-fix-crossというクラスのスタイルで、幅と高さをそろえるための幅0pxのtd、高さ0xのtdを4つのペインの境目に入れたこと。(以下の図の矢印のところに、visibility: hiddenで隠された行や列がある)

f:id:etsux:20170620225933p:plain

four_panes_table.css

幅と高さ調整のスタイルの定義は以下ではまった。

  • 行を0pxにするには、line-heightとoverflow:hiddenが必要。
  • min-width、max-widthで幅、min-height、max-heightで高さを制御。
  • !importantをつけないと別で定義されたスタイルが使われる。
#FourPanesTable-left-top {
	margin: 0px;
	padding: 0px;
	vertical-align: top;
	text-align: left;
	float: left;
	overflow: hidden;
}
#FourPanesTable-right-top {
	margin: 0px;
	padding: 0px;
	vertical-align: top;
	text-align: left;
	overflow: hidden;
}
#FourPanesTable-left-bottom {
	margin: 0px;
	padding: 0px;
	vertical-align: top;
	text-align: left;
	float: left;
	overflow: hidden;
	height: 50vh;
}
#FourPanesTable-right-bottom {
	margin: 0px;
	padding: 0px;
	vertical-align: top;
	text-align: left;
	overflow: scroll;
	height: 50vh;
}
td.FourPanesTable-fix-height {
	min-width: 0px !important;
	max-width: 0px !important;
	min-height: 1em;
	max-height: 1em;
	height: 1em;
	visibility: hidden !important;
}
td.FourPanesTable-fix-width {
	min-height: 0px !important;
	max-height: 0px !important;
	line-height:0px !important;
	overflow: hidden !important;
	visibility: hidden !important;
}
td.FourPanesTable-fix-cross {
	min-width: 0px !important;
	max-width: 0px !important;
	min-height: 0px !important;
	max-height: 0px !important;
	line-height: 0px !important;
	overflow: hidden !important;
	visibility: hidden !important;
}
#FourPanesTable-left-top table ,
#FourPanesTable-right-top table ,
#FourPanesTable-left-bottom table ,
#FourPanesTable-right-bottom table {
	table-layout: fixed;
}
#FourPanesTable-left-bottom table tr:nth-child(odd),
#FourPanesTable-right-bottom table tr:nth-child(odd) {
	background: #f0ffff;
}

four_panes_table.js

$(this).scrollLeft()は()を忘れてスクロールが同期されずはまった。

$(document).ready(function() {
	$('#FourPanesTable-right-bottom').scroll(function(){
		$('#FourPanesTable-right-top').scrollLeft($(this).scrollLeft());
		$('#FourPanesTable-left-bottom').scrollTop($(this).scrollTop());
	});
});