jQuery UIのsortableでtable並び替え(helperオプションで表示の修正)
jQuery UIのsortableを使ってtable要素を並び替えるの続きです。
例えば上のリンクのデモ画面を見ると、並び替えをしようとして行をドラッグすると移動中の行の幅が小さくなってしまっています。
例えば、このデモ画面を見ると、ドラッグ中にdivとかliの場合は幅が保存されているのに対してtableの場合は幅が保存されていません。なので、ちょっと見にくいです。
sortableではドラッグ時に移動中の要素(helperと呼びます)の幅を設定してくれます。これは元の要素の幅を動的に取得してhelperにも同じ幅を指定することで実現しています。
table内を並び替えする場合もhelperとなるtrの幅を設定してくれているのですが、trにはwidthを設定しても無視されるようです。
この解決策として、helperオプションを指定します。
コードを記載します。
html
<table id="sortable-table1"> <thead> <tr> <th>番号</th> <th>項目</th> <th>備考</th> </tr> </thead> <tbody> <tr> <td>1</td><td>項目1</td><td></td> </tr> <!-- 省略 --> </tbody> </table>
css
#sortable-table1 { width: 50%; border-collapse: collapse; } #sortable-table1 td, #sortable-table1 th { border: solid 1px black; }
javascript
$(function(){ $('#sortable-table1 tbody').sortable({helper: helper1, cursor: "move", opacity: 0.5}); }); function helper1(e, tr) { var $originals = tr.children(); var $helper = tr.clone(); $helper.children().each(function(index) { $(this).width($originals.eq(index).width()); }); return $helper; }
tr内のtdそれぞれに対してwidthを指定することでtableの行としての幅を保存できます。
このhelperというのはちょっと理解するのが難しいかもしれないです。
Sortable API(helper)