table で複数行の sortable

テーブルの Sortable 去年書いたけど、書き直す。ドラッグした後に、きちんとハンドルを外す。

sortable の stop オプションで、ui.item.data('multidrag') で取得した移動対象を移動後に
ui-selected を外してやります。

HTML

<table id="sortable">
  <thead>
     <tr><th>header-1</th><th>header-2</th></tr>
  </thead>
  <tbody>
     <tr><td>Item-1</td><td>aaa</td></tr>
     <tr><td>Item-2</td><td>bbb</td></tr>
     <tr><td>Item-3</td><td>ccc</td></tr>
     <tr><td>Item-4</td><td></td></tr>
     <tr><td>Item-5</td><td>eee</td></tr>
     <tr><td>Item-6</td><td></td></tr>
     <tr><td>Item-7</td><td>fff</td></tr>
     <tr><td>Item-8</td><td></td></tr>
     <tr><td>Item-9</td><td></td></tr>
     <tr><td>Item-10</td><td></td></tr>
    </tbody>
</table>

CSS

@CHARSET "UTF-8";

table{
   margin: 40px 50px;
   box-sizing: border-box;
   border-collapse; collapse;
   border-spacing: 0;
   white-space: nowrap;
}
th{ background-color: #c0c0c0; }
th,td{ border: 1px solid #444444; height: 40px; width: 100px; padding: 0 8px; }
.ui-selecting{ background-color: #feca40; }
.ui-selected{ background-color: #f39814; color: #ffffff; }
.ui-state-highlight{ background-color: #ffe45c; }

f:id:posturan:20160914003320j:plain


jQueury

$('#sortable tbody').selectable({
   cancel: '.sort-handle, .ui-selected',
}).sortable({
   placeholder: "ui-state-highlight",
   axis: 'y',
   opacity: 0.9,
   items: "> tr",
   handle: 'td, .sort-handle, .ui-selected',
   helper: function(e, item){
      if (!item.hasClass('ui-selected')){
         item.parent().children('.ui-selected').removeClass('ui-selected');
         item.addClass('ui-selected');
      }
      var selected = item.parent().children('.ui-selected').clone();
      ph = item.outerHeight() * selected.length;
      item.data('multidrag', selected).siblings('.ui-selected').remove();
      return $('<tr/>').append(selected);
   },
   cursor: "move",
   start: function(e, ui){
      ui.placeholder.css({'height':ph});
   },
   stop: function(e, ui){
      var selected = ui.item.data('multidrag');
      ui.item.after(selected);
      ui.item.remove();
      selected.removeClass('ui-selected');
      $(selected).children("td").removeClass('ui-selected');
   },
   update: function(e, ui){
      console.log("updated !!");
   }
});