CSS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | table.two-column { margin-bottom : 20px ; } table.two-column th, table.two-column td { border : 1px solid #aaa ; padding : 10px ; text-align : center ; } table.two-column tr:first-child { background-color : #ddd ; font-weight : bold ; color : #080 ; cursor : pointer ; } |
補足
- table 要素に付ける two-column クラスを定義。
- レイアウトが崩れる場合は リセットCSS・共通CSS の内容を確認。
jQuery
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | $( function (){ $( 'table.two-column tr:first-child *' ).on( 'click' , function (){ var table = $( this ).parents( 'table.two-column' ); if ( table.hasClass( 'on' ) ) { /* 既に2列表示の場合 */ table.find( 'th, td' ).css( 'display' , 'table-cell' ); /* 全てのセルを表示 */ table.removeClass( 'on' ); } else { /* 全列表示になっている場合 */ var col = $( this ).index(); /* クリックされた列 */ if ( 0 < col ) { /* 1列目以降がクリックされた場合 */ table.find( 'th, td' ).hide(); /* 全てのセルを一旦削除 */ table.find( 'tr' ).each( function (){ $( this ).children().eq(0).css( 'display' , 'table-cell' ); /* 左端の列を表示 */ $( this ).children().eq(col).css( 'display' , 'table-cell' ); /* クリックされた列を表示 */ }); table.addClass( 'on' ); } } }); }); |
補足
- このサンプルでは、テーブル1行目の商品名をクリックすると2列表示と全列表示が切り替わる(1行目左端の「商品名」をクリックした場合は、全列表示になる)。
- デモページで使用している jQuery のバージョンは 1.12.4 。
HTML
1 2 3 4 5 6 7 8 9 10 | < table class = "two-column" > < tbody > < tr >< th >商品名</ th >< th >ルミア</ th >< th >マロア</ th >< th >ミオン</ th ></ tr > < tr >< th >高さ:mm</ th >< td >500</ td >< td >300</ td >< td >600</ td ></ tr > < tr >< th >幅:mm</ th >< td >700</ td >< td >500</ td >< td >400</ td ></ tr > < tr >< th >奥行:mm</ th >< td >400</ td >< td >300</ td >< td >500</ td ></ tr > < tr >< th >重量:kg</ th >< td >1.5</ td >< td >2.2</ td >< td >3.2</ td ></ tr > < tr >< th >価格:円</ th >< td >6,000</ td >< td >3,800</ td >< td >7,500</ td ></ tr > </ tbody > </ table > |
補足
- クリックで2列表示と全列表示を切り替える table 要素に two-column クラスを付ける。