背景

允许用户按照自己喜欢的顺序设置表格的显示数据
我使用jQuery UIsortable 来设置HTML 表格项的顺序。

结果

jQueryを使ってテーブルの行をドラッグ&ドロップで並び替え

环境

  • jQuery: 1.8.3
  • jQuery UI:1.8.24

我试过的浏览器

以下是我测试过的浏览器列表。也可能支持其他浏览器。

  • Mozilla 火狐:103.0.2
  • 铬:104.0.5112.79
  • Microsoft Edge:104.0.1293.47
  • Safari:15.6

源代码

准备要排序的 HTML 表格

html
<table id="tblLocations" cellpadding="0" cellspacing="0" border="1">
    <tr>
        <th>ID </th>
        <th></th>
        <th>並び替え</th>
    </tr>
    <tr>
        <td>1</td>
        <td>Red</td>
        <td>1</td>
    </tr>
    <tr>
        <td>2</td>
        <td>Green</td>
        <td>2</td>
    </tr>
    <tr>
        <td>3</td>
        <td>Blue</td>
        <td>3</td>
    </tr>
    <tr>
        <td>4</td>
        <td>Yellow</td>
        <td>4</td>
    </tr>
    <tr>
        <td>5</td>
        <td>Purple</td>
        <td>5</td>
    </tr>
</table>

加载 jQuery 和 jQueryUI

html
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/jquery-ui.min.js"></script>

配置 jQuery UI 可排序插件

html
<script type="text/javascript">
    $(function () {
        $("#tblLocations").sortable({
            // 見出しである一番上の行以外をドラッグできるように設定
            items: 'tr:not(tr:first-child)',
            // マウスカーソルの形状を変える
            cursor: 'pointer',
            // ドラッグできる方向は縦方向のみなのでaxisに(y)を設定
            axis: 'y',
            // ドラッグされた行が明確に見えるようにstartイベントにselectedクラスを設定
            start: function (e, ui) {
                ui.item.addClass("selected");
            },
            // ドロップした行のselectedクラスを解除して並び替え列を更新
            stop: function (e, ui) {
                ui.item.removeClass("selected");
                $(this).find("tr").each(function (index) {
                    // index = 0は見出しの行ですから更新しない
                    if (index > 0) {
                        $(this).find("td").eq(2).html(index);
                    }
                });
            }
        });
    });
</script>

为设计准备 CSS

html
<style type="text/css">
    table
    {
        border: 1px solid #ccc;
        border-collapse: collapse;
    }
    table th
    {
        background-color: #F7F7F7;
        color: #333;
        font-weight: bold;
    }
    table th, table td
    {
        width: 100px;
        padding: 5px;
        border: 1px solid #ccc;
    }
    .selected
    {
        background-color: #54C500;
        color: #fff;
    }
</style>

想法

原以为拖拽排序功能会比较难,但实际试用后发现jQuery UI Sortable插件好懂,比想象中简单。

参考


原创声明:本文系作者授权爱码网发表,未经许可,不得转载;

原文地址:https://www.likecs.com/show-308623719.html

相关文章:

  • 2022-12-23
  • 2022-03-10
  • 2021-09-04
  • 2022-12-23
  • 2022-02-26
  • 2021-07-11
  • 2021-12-03
猜你喜欢
  • 2022-12-23
  • 2022-01-07
  • 2021-07-12
  • 2021-10-10
  • 2021-10-02
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案