WEBOPIXEL

jQueryでTableにマウスオーバーすると拡大(詳細)表示する

Posted: 2012.03.23 / Category: javascript / Tag: 

Table(表)に情報量が多い表を入れようとすると改行がたくさん入り、読みにくくなってしまうことがあります。
そこで、普段は最小限の項目を表示してjQueryでマウスオーバーすると詳細な情報が表示されるということをしてみます。

Sponsored Link

テーブル全体を拡大するタイプ

demo

たとえばこんな普通の表があったとします。

html

	<table class="table01">
		<thead>
			<tr>
				<th>ID</th>
				<th>タイトル</th>
				<th>URL</th>
				<th>説明</th>
				<th>公開日</th>
			</tr>
		</thead>
		<tbody>
			<tr>
				<td>10000000</td>
				<td>1行目のタイトル</td>
				<td>http://www.example.com/</td>
				<td>これは1行目のあれなのです。</td>
				<td>2012.04.21</td>
			</tr>
			<tr>
				<td>10000001</td>
				<td>2行目のタイトル</td>
				<td>http://www.example.com/</td>
				<td>これは2行目のあれなのです。</td>
				<td>2012.02.01</td>
			</tr>
			...
		</tbody>
	</table>
	

cssは最低限「position」と「z-index」を指定しておきます。

css

	table {
		width: 100%;
		position: relative;
		z-index: 5;
	}
	

この表の4,5列目の表示と非表示を切り替えたい場合jQueryのコードは以下のようになります。

javascript

	$(function() {
		var table = $('table.table01');
		//最初は4.5列目を非表示
		$('th:nth-child(4)', table).hide();
		$('th:nth-child(5)', table).hide();
		$('td:nth-child(4)', table).hide();
		$('td:nth-child(5)', table).hide();
		table.hover(
			function(){
				$(this).css('width', '800px');
				$('th:nth-child(4)', table).show();
				$('th:nth-child(5)', table).show();
				$('td:nth-child(4)', table).show();
				$('td:nth-child(5)', table).show();
			}, function() {
				$(this).css('width', '100%');
				$('th:nth-child(4)', table).hide();
				$('th:nth-child(5)', table).hide();
				$('td:nth-child(4)', table).hide();
				$('td:nth-child(5)', table).hide();
			}
		);
	});
	

ちょっと無駄が多い気がしますが、「:nth-child(n)」でn番目の列を選択できますので、あとはマウスオーバーで「show()」「hide()」すれば表示・非表示を切り替えられます。

テーブル行が拡大するタイプ

次は行ごとに拡大してみます。

demo

行の拡大は別要素で表示しますので、新たに下記のhtmlを追加します。

html

	<div id="popup">
		<table>
			<thead>
				<tr>
					<th>ID</th>
					<th>タイトル</th>
					<th>URL</th>
					<th>説明</th>
					<th>公開日</th>
				</tr>
			</thead>
			<tbody>
				<tr>
					<td></td>
					<td></td>
					<td></td>
					<td></td>
					<td></td>
				</tr>
			</tbody>
		</table>
	</div>
	

css

	#popup {
		width: 800px;
		position: absolute;
		display: none;
	}
	

jQueryではマウスオーバーした行の情報をpopupにいれて表示。
ポップアップからマウスアウトしたら非表示ということをしています。

javascript

	$(function() {
		var table = $('table.table-basic');
		var popup = $('#popup');
		//4,5列目非表示
		$('th:nth-child(4)', table).hide();
		$('th:nth-child(5)', table).hide();
		$('td:nth-child(4)', table).hide();
		$('td:nth-child(5)', table).hide();
		//popupテーブルに対してセンター配置
		popup.css('left' , table.offset().left- ((popup.outerWidth(true) - table.outerWidth(true) ) / 2) +'px');
		$('tbody tr', table).mouseover(function(){
			$('td', this).each(function(i){
				$('td',popup).eq(i).text($(this).text());
			});
			popup
				.css('top' , $(this).offset().top+'px')
				.show(); 
		});
		popup.mouseout(function(){
			$(this).hide();
		});
	});