Layui-table 表格拖拽

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Layui 表格拖拽</title>
    <script src="https://cdn.jsdelivr.net/npm/layui@2.9.21/dist/layui.min.js"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/layui@2.9.21/dist/css/layui.min.css">
    <!-- 确保在 layui 之后引入插件 -->
    <script src="./layui-table-drag.js"></script>
</head>
<body>
    <div style="padding: 20px;">
        <table id="demoTable" lay-filter="demoTable"></table>
    </div>

    <script>
    layui.use(['table'], function(){
        var table = layui.table;
             // 生成模拟数据
        function generateData(num) {
            var data = [];
            var cities = ['北京', '上海', '广州', '深圳', '成都', '杭州'];
            for (var i = 0; i < num; i++) {
                data.push({
                    id: i + 1,
                    username: '用户' + (i + 1),
                    age: Math.floor(Math.random() * 30) + 20, // 随机年龄 20-50
                    city: cities[Math.floor(Math.random() * cities.length)],
                    score: Math.floor(Math.random() * 100) + 50 // 随机分数 50-100
                });
            }
            return data;
        }
        // 渲染表格
        table.render({
            elem: '#demoTable',
            id: 'testTable',    // 一定要设置id
            data: generateData(20),  // 生成1000条数据 
            cols: [[
                {field: 'id', title: 'ID', width: 80, fixed: 'left'},
                {field: 'username', title: '用户名', width: 120, fixed: 'left'},
                {field: 'age', title: '年龄', width: 120},
                {field: 'city', title: '城市', width: 120},
                {field: 'score', title: '语文', width: 120}, 
                {field: 'score', title: '数学', width: 120}, 
                {field: 'score', title: '英语', width: 120}, 
                {field: 'score', title: '总分', width: 120}
            ]],
            done: function() {
                // 在表格渲染完成后初始化拖拽
                setTimeout(() => {
                    new LayuiTableDrag({
                        elem: 'testTable',     // 表格元素ID
                        id: 'testTable',       // 表格ID
                        table: table,          // table实例
                        done: function(data) { // 拖拽完成的回调
                            console.log('数据更新了:', data);
                        }
                    });
                }, 100);
            }
        });
    });
    </script>
</body>
</html>

关键 layui-table-drag.js文件

/**
 * LayuiTableDrag 插件
 * author: webrs - lingfeng
 * v1.0.0
 */
(function (window) {
  "use strict";
  class LayuiTableDrag {
    constructor(config = {}) {
      // 必要参数检查
      if (!config.elem || !config.table || !config.id) {
        console.error("LayuiTableDrag: elem、table、id 是必须的配置项");
        return;
      }
      this.config = Object.assign(
        {
          trigger: "row", // 触发方式: row=整行触发, cell=第一列触发
          triggerClass: "", // 自定义触发元素的类名
          done: null, // 拖拽完成的回调函数
        },
        config
      );
      this.table = this.config.table;
      this.tableId = this.config.id;
      this.elem =
        typeof config.elem === "string"
          ? config.elem.charAt(0) === "#"
            ? config.elem
            : "#" + config.elem
          : "#" + config.elem.attr("id");
      this.tableView = `div[lay-table-id="${this.tableId}"]`;
      this.waitForTable();
    }
    waitForTable() {
      const timeoutLimit = 3000;
      const startTime = Date.now();
      const checkTable = () => {
        const tableView = document.querySelector(this.tableView);
        if (tableView) {
          this.init();
        } else if (Date.now() - startTime < timeoutLimit) {
          setTimeout(checkTable, 50);
        } else {
          console.error("LayuiTableDrag: 表格加载超时");
        }
      };
      checkTable();
    }
    init() {
      const tableView = document.querySelector(this.tableView);
      if (!tableView) {
        console.error("LayuiTableDrag: 未找到指定的表格视图元素");
        return;
      }
      this.injectStyle();
      this.initObserver();
      this.bindEvents();
    }

    injectStyle() {
      if (!document.getElementById("layui-table-drag-style")) {
        const style = document.createElement("style");
        style.id = "layui-table-drag-style";
        style.textContent = `
                    .layui-table-drag-trigger {
                        cursor: move;
                    }
                    .layui-table-drag-dragging {
                        opacity: 0.6;
                        background: #e6f7ff !important;
                    }
                    .layui-table-drag-target {
                        border-top: 2px dashed #1E9FFF !important;
                    }
                    ${this.tableView} .layui-table-body tr {
                        cursor: move;
                    }
                `;
        document.head.appendChild(style);
      }
    }

    initObserver() {
      if (this.observer) return;
      this.observer = new MutationObserver(() => {
        this.bindEvents();
      });
      const tables = document.querySelectorAll(
        `${this.tableView} .layui-table-body table`
      );
      if (tables.length > 0) {
        tables.forEach((table) => {
          this.observer.observe(table, {
            childList: true,
            subtree: true,
          });
        });
      } else {
        console.warn("LayuiTableDrag: 未找到表格体元素,无法初始化观察者");
      }
    }
    getAllTableBodies() {
      const mainTable = document.querySelector(
        `${this.tableView} .layui-table-main.layui-table-body table`
      );
      const leftTable = document.querySelector(
        `${this.tableView} .layui-table-fixed-l .layui-table-body table`
      );
      const rightTable = document.querySelector(
        `${this.tableView} .layui-table-fixed-r .layui-table-body table`
      );
      return [mainTable, leftTable, rightTable].filter((el) => el);
    }
    bindEvents() {
      const mainBody = document.querySelector(
        `${this.tableView} .layui-table-main.layui-table-body`
      );
      const leftBody = document.querySelector(
        `${this.tableView} .layui-table-fixed-l .layui-table-body`
      );
      const rightBody = document.querySelector(
        `${this.tableView} .layui-table-fixed-r .layui-table-body`
      );
      const bodies = [mainBody, leftBody, rightBody].filter((el) => el);
      bodies.forEach((body) => {
        const rows = body.getElementsByTagName("tr");
        Array.from(rows).forEach((row) => {
          row.removeEventListener("dragstart", this.handleDragStart);
          row.removeEventListener("dragend", this.handleDragEnd);
          row.removeEventListener("dragover", this.handleDragOver);
          row.removeEventListener("dragleave", this.handleDragLeave);
          row.removeEventListener("drop", this.handleDrop);
          this.bindRowEvents(row);
        });
      });
      if (mainBody && leftBody) {
        mainBody.addEventListener("scroll", () => {
          leftBody.scrollTop = mainBody.scrollTop;
        });
      }
      if (mainBody && rightBody) {
        mainBody.addEventListener("scroll", () => {
          rightBody.scrollTop = mainBody.scrollTop;
        });
      }
    }

    bindRowEvents(row) {
      row.setAttribute("draggable", "true");
      row.addEventListener("dragstart", (e) => this.handleDragStart(e, row));
      row.addEventListener("dragend", (e) => this.handleDragEnd(e, row));
      row.addEventListener("dragover", (e) => this.handleDragOver(e, row));
      row.addEventListener("dragleave", (e) => this.handleDragLeave(e, row));
      row.addEventListener("drop", (e) => this.handleDrop(e, row));
    }
    handleDragStart(e, row) {
      e.stopPropagation();
      const index = this.getRowIndex(row);
      e.dataTransfer.setData("text/plain", index);
      e.dataTransfer.effectAllowed = "move";
      this.addClassToRow(index, "layui-table-drag-dragging");
      const dragImage = row.cloneNode(true);
      dragImage.style.opacity = "0.5";
      document.body.appendChild(dragImage);
      e.dataTransfer.setDragImage(dragImage, 0, 0);
      setTimeout(() => document.body.removeChild(dragImage), 0);
    }

    handleDragEnd(e, row) {
      e.stopPropagation();
      const index = this.getRowIndex(row);
      this.removeClassFromRow(index, "layui-table-drag-dragging");
      this.removeClassFromAllRows("layui-table-drag-target");
      this.bindRowEvents(row);
    }

    handleDragOver(e, row) {
      e.preventDefault();
      e.stopPropagation();
      const index = this.getRowIndex(row);
      this.removeClassFromAllRows("layui-table-drag-target");
      this.addClassToRow(index, "layui-table-drag-target");
    }

    handleDragLeave(e, row) {
      e.preventDefault();
      e.stopPropagation();
      const index = this.getRowIndex(row);
      this.removeClassFromRow(index, "layui-table-drag-target");
    }

    handleDrop(e, row) {
      e.preventDefault();
      e.stopPropagation();

      const sourceIndex = parseInt(e.dataTransfer.getData("text/plain"));
      const targetIndex = this.getRowIndex(row);

      if (sourceIndex === targetIndex) return;

      this.moveData(sourceIndex, targetIndex);

      this.removeClassFromAllRows("layui-table-drag-dragging");
      this.removeClassFromAllRows("layui-table-drag-target");
    }

    getRowIndex(row) {
      return Array.from(row.parentElement.children).indexOf(row);
    }

    addClassToRow(index, className) {
      this.getAllTableBodies().forEach((body) => {
        const row = body.rows[index];
        if (row) row.classList.add(className);
      });
    }

    removeClassFromRow(index, className) {
      this.getAllTableBodies().forEach((body) => {
        const row = body.rows[index];
        if (row) row.classList.remove(className);
      });
    }

    removeClassFromAllRows(className) {
      document.querySelectorAll(`${this.elem} .${className}`).forEach((el) => {
        el.classList.remove(className);
      });
    }

    moveData(sourceIndex, targetIndex) {
      const data = this.table.cache[this.tableId];
      if (!data || !Array.isArray(data)) return;
      const [movedItem] = data.splice(sourceIndex, 1);
      data.splice(targetIndex, 0, movedItem);

      this.table.reload(this.tableId, {
        data: data,
        done: () => {
          this.bindEvents();
          if (typeof this.config.done === "function") {
            this.config.done(data);
          }
        },
      });
    }

    destroy() {
      if (this.observer) {
        this.observer.disconnect();
        this.observer = null;
      }

      const style = document.getElementById("layui-table-drag-style");
      if (style) style.remove();

      this.getAllTableBodies().forEach((table) => {
        Array.from(table.rows).forEach((row) => {
          row.removeAttribute("draggable");
        });
      });
    }
  }

  // 注册到 layui
  if (typeof layui !== "undefined") {
    layui.define(["table"], function (exports) {
      exports("tableDrag", LayuiTableDrag);
    });
  }

  // 同时支持全局访问
  window.LayuiTableDrag = LayuiTableDrag;
})(window);

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,546评论 6 507
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,224评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,911评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,737评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,753评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,598评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,338评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,249评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,696评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,888评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,013评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,731评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,348评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,929评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,048评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,203评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,960评论 2 355

推荐阅读更多精彩内容