[jQuery]讓table的每一列tr可以用拖拉的方式改變位置

  • 2892
  • 0
  • 2020-06-16

[jQuery]讓table的每一列tr可以用拖拉的方式改變位置

參考網路上codepen高人的,自己做紀錄一下,下面有他的html, css, js可參考
自己實際測試成功的時候,只要修改自己程式碼的js即可,html以及css不需要改

html:

<div class="responsive-table">
  <table id="sortable">
    <tr class="ui-state-default">
      <th>Drag Row</th>
      <th>Id</th>
      <th>Fruit</th>
      <th>Quantity</th>
      <th>Image</th>
    </tr>
    <tr>
      <td><i class="fa fa-bars"></i></td>
      <td data-id="1">1</td>
      <td>Apple</td>
      <td>5</td>
      <td><img src="" alt="noImage" width="30px" height="25px"></td>
    </tr>
    <tr>
      <td><i class="fa fa-bars"></i></td>
      <td data-id="2">2</td>
      <td>Orange</td>
      <td>8</td>
      <td><img src="" alt="noImage" width="30px" height="25px"></td>
    </tr>
    <tr>
      <td><i class="fa fa-bars" ></i></td>
      <td data-role="test" data-id="3">3</td>
      <td>Banana</td>
      <td>3</td>
      <td><img src="" alt="noImage" width="30px" height="25px"></td>
    </tr>
  </table>
</div>


css:

@import url(https://fonts.googleapis.com/css?family=Open+Sans);

* {
  font-family: 'Open Sans', sans-serif;
}

.responsive-table {
  overflow: auto;
}

table {
  width: 100%;
  border-spacing: 0;
  border-collapse: collapse;
  white-space:nowrap;
}

table th {
  background: #BDBDBD;
}

table tr:nth-child(odd) {
  background-color: #F2F2F2;
}
table tr:nth-child(even) {
  background-color: #E6E6E6;
}

th, tr, td {
  text-align: center;
  border: 1px solid #E0E0E0;
  padding: 5px;
}

img {
  font-style: italic;
  font-size: 11px;
}

.fa-bars{
  cursor: move;
}


js:

  $(function() {
    $("#sortable tbody").sortable({
	  items: "tr:not(:first)",//排除header(看自己需要決定)
      cursor: "move",
      placeholder: "sortable-placeholder",
      helper: function(e, tr)
      {
        var $originals = tr.children();
        var $helper = tr.clone();
        $helper.children().each(function(index)
        {
        // Set helper cell sizes to match the original sizes
        $(this).width($originals.eq(index).width());
        });
        return $helper;
      }
    }).disableSelection();
  });

引用的css以及js如下:
https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css
https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js
https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js

作者的codepen的實測畫面(拖拉前):

拖拉中:

拖拉完畢:

非常神奇的功能!



參考資料:
https://codepen.io/orist/pen/bVmzoK
https://jqueryui.com/sortable/#default