motogp fan

motogp ファンによる、雑ブログ、ガジェットネタも

はてなブログでプログラムを学ぼう9 jQueryでCSSの切替

はてなブログ内でjavaScriptjQuery勉強中。 

今回は表のレイアウトをワンタッチで切り替えてみよう

Googleカレンダーの日、週、月切替みたいな機能が必要になったので検討しました。

割と簡単に実現する方法として、css複数パターン用意して、表の代表class名を変更する方法。

簡単に説明すると

  1. cssを2個用意
    .tbl1{width: 600px;}
    .tbl2{width: 1400px;}
  2. HTMLにidとclassを指定
    <table id="tbl" class="tbl1">
    <tbody>
  3. jQueryで切り替える(クリックした時に切り替える)
    jQueryだとclassを消して、追加する操作が必要
    $('#btn1') //idを指定(パターン1のボタン)
    .on('click', function(){
      $('#tbl').removeClass('tbl2');
      $('#tbl').addClass('tbl1');
    });
    $('#btn2') //idを指定(パターン2のボタン)
    .on('click', function(){$('#tbl').removeClass('tbl1');$('#tbl').addClass('tbl2');});

 

例として縮小と拡大の2つのレイアウトを切り替えてみます。

以下テスト

 拡大ボタンで列の幅を広くできます。

 10111213
ロッシ 25 16 25 16 20 16 20 25 16 16 16 25 11
ロレンソ 13 13 11 25 25 25 25 16 13 20 25 13 -
マルケス 11 25 - 20 13 - - 20 25 25 20 - 25

 

 

以上

 

motagp.hatenablog.com

 

 

以下SAMPLE抜粋

 CSS-----------------------------

.tbl1{
width: 600px;
border-collapse: collapse;
table-layout: fixed;
}
.tbl1 th{
width: 15px;
padding: 6px;
text-align: left;
vertical-align: top;
color: #333;
background-color: #eee;
border: 1px solid #b9b9b9;
}
.tbl1 td{
padding: 6px;
background-color: #fff;
border: 1px solid #b9b9b9;
}
.tbl1 tr th:nth-of-type(1) {
width: 80px;
}
.tbl2{
width: 1900px;
border-collapse: collapse;
}
.tbl2 th{
width: 100px;
padding: 6px;
text-align: left;
vertical-align: top;
color: #333;
background-color: #eee;
border: 1px solid #b9b9b9;
}
.tbl2 td{
padding: 6px;
background-color: #fff;
border: 1px solid #b9b9b9;
}
.tbl2 tr th:nth-of-type(1) {
width: 80px;
}

HTML抜粋--------------

 <table id="tbl" class="tbl1"> このクラス名を変化させる
<tbody>

 JQuery--------------------------------------------------

 $(function() {
$('#btn1')
.on('click', function(){
//document.getElementById("tbl").className = "tbl1"; //javaScriptの例
$('#tbl').removeClass('tbl2');
$('#tbl').addClass('tbl1');
});
$('#btn2')
.on('click', function(){
//document.getElementById("tbl").className = "tbl2"; //javaScriptの例
$('#tbl').removeClass('tbl1');
$('#tbl').addClass('tbl2');
});
});