layui table表格的应用

3/15/2023 11:25:29 AM
962
0

layui  table表格拖拽宽度记忆和表格拖拽滑动滚动条和表格右键菜单的应用。效果如下

 

HTML表格部分

    <div class="layui-panel">
        <div class="panel-body">
            <div class="layui-card" id="seachpan" style="border-bottom:none; box-shadow:none; margin-bottom:0;">

                <div class="layui-card-body" style=" " id="doccontent">
                    <input id="docNumber" type="hidden" value="">
                    <table lay-even lay-skin="row" class="layui-hide" id="reply-table" lay-filter="reply-table"></table>
                </div>
            </div>
        </div>
    </div>

注册按键监测功能

        var globalKeyEvent = null;
        var globalClickEvent = null;
        document.onkeydown = function(event) {
            event = event || window.event;

            /*
             * 可以通过keyCode来获取按键的编码
             * 	通过它可以判断哪个按键被按下
             * 除了keyCode,事件对象中还提供了几个属性
             * 	altKey
             * 	ctrlKey
             * 	shiftKey
             * 		- 这个三个用来判断alt ctrl 和 shift是否被按下
             * 			如果按下则返回true,否则返回false
             */

            //console.log(event.keyCode);

            //判断一个y是否被按下
            //判断y和ctrl是否同时被按下
            if (event.keyCode === 89 && event.ctrlKey) {
                console.log("ctrl和y都被按下了");
            }
            globalKeyEvent = event;

        };

        document.onkeyup = function(event) {
            globalKeyEvent = event;
        };
        document.onmousedown = function(event) {
            globalClickEvent = event;
        };
        document.onmouseup = function(event) {
            globalClickEvent=null;
            globalKeyEvent = null;
        };

 

注册css  layui table默认表格鼠标样式使用指针,这里去除table上的表格指针样式设置,用以继承父元素的鼠标指针样式

        fieldset * {
            all: revert;
        }

        .layui-table-view .layui-table td{
            cursor:revert;
        } 

 

执行拖拽滚动的函数。主要功能实现按下Ctrl 时候拖动 table 实现滚动条滚动。模拟触摸滑动效果


        function dragTable() {
         
            let scrollContainer = document.querySelector(".layui-table-main");
            scrollContainer.onmousedown = e => {
                  if (!globalKeyEvent || !globalKeyEvent.ctrlKey) {  //监测按键 Ctrl

                      return;
                  }

                if (e.button == 2) {
                    return;
                }
                //let dragStats = false;
                //var setCursorImplement = setTimeout(function() {
                    scrollContainer.style.cursor = "move"
                    dragStats = true;
                //}, 10);

                //鼠标按下那一刻,滚动条的位置
                let mouseDownScrollPosition = {
                    scrollLeft: scrollContainer.scrollLeft,
                    scrollTop: scrollContainer.scrollTop
                };

                //鼠标按下的位置坐标
                let mouseDownPoint = {
                    x: e.clientX,
                    y: e.clientY
                };




                scrollContainer.onmousemove = e => {
                    if (dragStats) {
                        //鼠标滑动的实时距离
                        let dragMoveDiff = {
                            x: mouseDownPoint.x - e.clientX,
                            y: mouseDownPoint.y - e.clientY
                        };
                        scrollContainer.scrollLeft = mouseDownScrollPosition.scrollLeft + dragMoveDiff.x;
                        scrollContainer.scrollTop = mouseDownScrollPosition.scrollTop + dragMoveDiff.y;

                        //取消选中
                        e.preventDefault();//阻止默认事件,取消文字选中
                    }
                    else {
                        
                    }
                };

                document.onmouseup = e => {
                    scrollContainer.onmousemove = null;
                    document.onmouseup = null;
                    scrollContainer.style.cursor = "";
                };

            };
        }

 

layui table 执行时机,实现了列宽的记忆、table右键菜单、和执行按下Ctrl时候的左键拖拽滑动效果

  table.render({
                id: "testReload",
                elem: '#reply-table',
                url: "./xxxx/xxxxx",   //数据接口
                ajaxGlobal: false,
                method: 'get',
                title: 'xxxxx管理',
                toolbar: '#test-table-toolbar-tool',
                defaultToolbar: ['filter', 'print', 'exports', {
                    title: '提示' //标题
                    , layEvent: 'LAYTABLE_TIPS' //事件名,用于 toolbar 事件中使用
                    , icon: 'layui-icon-tips' //图标类名
                }],
                global: false,
                parseData: parseDataFun,   //接口数据格式化函数 
                request: {
                    pageName: "page",
                    limitName: "size"
                },
                where: {},
                loading: false,
                limit: 15,
                cols: [function() {

                    var arr = [{ type: 'checkbox' },
                    {
                        field: 'name',
                        title: '联系人',
                     
                        width: 100,
                        templet: function(d) {
                            return (d.badge ? '<span class="layui-badge-dot"></span>' : '') + '<a href="./xxx/xxxxx/' + d.id + '" target="_blank" class="layui-font-blue">' + d.name + '</a> ';
                        }
                    },
                    {
                        field: 'phone',
                        title: '手机',
                           event:"phone",
                        class: "ts",
                        width: 120
                    },
                    {
                        field: 'originName',
                        title: '来源',
                        width: 100,
                        filter: true
                    },
                    {
                        field: 'stage',
                        title: '阶段',
                        width: 80,
                        filter: true
                    },
                    {
                        field: 'stateName',
                        title: '状态',
                        width: 120,
                        filter: true
                    },
                    {
                        field: 'userRealName',
                        title: '所属人',
                        width: 80
                    },
                    {
                        field: 'belongSection',
                        title: '部门',
                        width: 100,
                        templet: function(d) {
                            if (d.belongSection) {
                                return d.belongSection.name;
                            }
                            return "";
                        }
                    },
                    {
                        field: 'priority',
                        title: '等级',
                        width: 80,
                        filter: true
                    },
                    {
                        field: 'priorityDescribe',
                        title: '客户描述',
                        width: 440
                    },
                    {
                        field: 'email',
                        title: '邮箱',
                        width: 100
                    },
                    {
                        field: 'outflowTime',
                        title: '转出时间',
                        width: 160,
                        templet: function(d) {
                            if (d.outflowTime > 0) {
                                return (new Date(d.outflowTime * 1000)).format("yyyy-MM-dd HH:mm:ss");
                            }
                            return "";
                        }
                    },
                    {
                        field: 'receiveTime',
                        title: '转入时间',
                        width: 160,
                        templet: function(d) {
                            if (d.receiveTime > 0) {
                                return (new Date(d.receiveTime * 1000)).format("yyyy-MM-dd HH:mm:ss");
                            }
                            return "";
                        }
                    },
                    {
                        field: 'created',
                        title: '创建时间',
                        width: 160,
                        templet: function(d) {
                            return (new Date(d.created * 1000)).format("yyyy-MM-dd HH:mm:ss");
                        }
                    },

                    {
                        field: 'company',
                        title: '公司名称',
                        width: "30%",
                        minWidth: "5em"

                    },
                    {
                        field: 'trade',
                        title: '行业',
                    },
                    {
                        field: 'fosterName',
                        title: '培育人',
                        width: "150"
                    },
                    {
                        field: 'intentionProductName',
                        title: '意向产品',
                        width: "150"
                    },
                    {
                        field: 'commpanyNatureName',
                        title: '企业性质',
                        width: "150"
                    }];

                    //初始化筛选状态
                    var local = layui.data('table-filter-test');
                    var localColWidth = layui.data("table-col-width");
                    layui.each(arr, function(index, item) {
                        if (item.field in local) {      //监测筛选列,使隐藏的列被隐藏
                            item.hide = local[item.field];
                        }

                        if (item.field in localColWidth) {  //初始化列宽,当用户拖拽列宽后被记忆,在这里绘制表格时候使用记忆中的列宽
                            item.width = localColWidth[item.field];
                        }
                    });
                    return arr;
                }()],
                page: true,
                height: 'full-100',
                done: function(res, curr, count) {
                    if (top.delClueBadge != undefined) {
                        top.delClueBadge();
                    }
		    
		    //通过对数据属性比较,对表格一行进行着色
                    res.data.forEach(function(item, index) {  
                        if (item.state == "丢弃") {
                            var tr = $(".layui-table").find("tbody tr[data-index='" + index + "']");
                            tr.css({ "background-color": "#9e9e9e", "color": "#ffff" });
                        }
                    });

    		    //为表格创建鼠标右键操作
                    $('.layui-table-body tr').each(function(e) {
                        $(this).mousedown(function(e) {
                            var index = $(this).attr('data-index'); //获取该表格行的数据
                            $(this).addClass("slrow").siblings().removeClass("slrow");
                            if (e.which == 3) { //判断时鼠标右键按下
                                trdata = res.data[index]; //将该行的数据存放到自己定义的变量中
                                console.log(trdata);
                                cluemouseDown(trdata, this);
                            }
                        });
                    });

        
                    //记录筛选状态
                    var that = this;
                    that.elem.next().on('mousedown', 'input[lay-filter="LAY_TABLE_TOOL_COLS"]+', function() {
                        var input = $(this).prev()[0];
                        layui.data('table-filter-test',
                            {
                                key: input.name,
                                value: input.checked
                            })
                    });

                    dragTable();  //拖拽table 实现滑动
                }
            });

 

table右键菜单


        //右键菜单,要先生成,
         var inst = dropdown.render({
                elem: '#xxxx' //随便搞一个元素,就行
                , trigger: 'contextmenu' //contextmenu
                , isAllowSpread: false //禁止菜单组展开收缩

                , id: 'test777' //定义唯一索引
                , data: [],
                click: function(obj, othis) {
                     //菜单点击事件处理程序
                }
            });

        /*右键处理程序*/
        function cluemouseDown(model, elem) {
            var power = model.cluePower;
            var menuArr = [];
            menuArr.push({ title: "查看", id: "open", data: model });
            menuArr.push({ type: '-' });
           

            menuArr.push({ type: '-' });
           
            for (var i = 0; i < power.length; i++) {
                menuArr.push({ title: power[i], id: power[i], data: model });
            }

            dropdown.reload('菜单id', {
                data: menuArr,
                style: "box-shadow:5px 5px 6px 0px rgb(0 0 0/ 69%);border: 1px solid #c0c0c0;",  //菜单不明显,设置边框颜色和阴影
                elem: elem     //菜单绑定的元素/节点
            });
        }

 

table表格拖拽宽度的记忆

            table.on('colResized(reply-table)', function(obj) {
                console.log(obj);
                var col = obj.col;
                layui.data('table-col-width', { key: col.field, value: col.width })

            });

table表格事件处理程序

// 双击表格中的某一行-触发行双击事件
table.on('rowDouble(reply-table)', function(obj) {

}
// 监听单元格点击事件
table.on('tool(reply-table)', function(obj) {
	console.log(obj);         
}
//选中行事件
table.on('checkbox(reply-table)', function(obj) { 

}
                                  

全部评论



提问