layui列表多功能-列固定,排序,固定赛选,导出重写,监听弹窗返回 刷新保留缓存 横向滑动固定

<link rel="stylesheet" href="mode/layui/css/soulTable.css" media="all">
<script type="text/html" id="myBar">
    <div>
        <button class="layui-btn layui-btn-primary layui-btn-xs" οnclick="outall()" id="outall"  >导出</button>
        列拖拽: <input type="checkbox" lay-skin="switch" lay-filter="rowDragSwitch" lay-text="启用|暂停" >
    </div>
</script>
<script>
    window.scrollLeft=0;
    var tableCols =[];
    var ins;
    var local_storage_key = num;//项目里每张表格取一个特有的名字
    ecelBase = '/mode/layui/ext/';
    layui.config({
        version: '', //为了更新 js 缓存,可忽略
        base:ecelBase
        
    }).extend({
        soulTable: 'soulTable',//列固定
        tableChild: 'tableChild',
        tableMerge: 'tableMerge',
        tableFilter: 'tableFilter',
        excel: 'excel',
    });
   defaultConfig = { // 默认配置开关
        fixTotal: false, // 修复合计行固定列问题
        drag: false, // 列拖动
        rowDrag: false, // 行拖动
        autoColumnWidth: false, // 自动列宽
        contextmenu: false, // 右键菜单
        fixResize: false, // 修改有固定列的拖动列宽的位置为左边线
        overflow: false, // 自定义内容超出样式
        fixFixedScroll: true, // 固定列支持鼠标滚轮滚动
        filter: true  // 筛选及记忆相关
    };
    layui.use(['jquery', 'layer', 'tree', 'element', 'laypage', 'table', 'laydate', 'form', 'soulTable'],function () { //亦可加载特定模块:layui.use(['layer', 'laydate', function(){
        var layer = layui.layer //弹层
            , laypage = layui.laypage //分页
            , $ = layui.$
            , laydate = layui.laydate //日期
            , table = layui.table //表格
            , carousel = layui.carousel //轮播
            , upload = layui.upload //上传
            , form = layui.form
            , element = layui.element //元素操作
            , slider = layui.slider //滑块
            , dropdown = layui.dropdown //下拉菜单
            window['layui']=layui;

    });

    window.layui.form.render(null, 'component-form-element');
    window.layui.element.render('breadcrumb', 'breadcrumb');
 //监听Tab切换
        window.layui.element.on('tab(test-table-operate)', function (data) {
            layer.tips('切换了 ' + data.index + ':' + this.innerHTML, this, {
                tips: 1
            });
        });
    $('#clear').on('click', function() {
        window.layui.soulTable.clearCache(ins.config.id)
        layer.msg('已还原!', {icon: 1, time: 1000})
    })
    //表格 头部数据函数封装
    function getTableCols(){
        var col = [
                ,{width: 150, align: 'center', fixed: 'right', toolbar: '#test-table-operate-barDemo'}
            ];
        return col;
    }
     tableCols = tableSetCol(getTableCols(), local_storage_key);//根据local_storage保留表格情况
       ins =  window.layui.table.render({
            elem: '#test-table-operate'
            ,url: url
            ,id:'test-table-operate'
            ,title:''
            ,limits: limits
            , limit: limit
            ,page: true //开启分页
            ,method: 'post'
            ,header: {
                Cookie: document.cookie
            }
            ,where: {

            }
            ,toolbar: '#myBar'
            ,defaultToolbar: ["filter", "exports"]
            //,toolbar: true //开启工具栏,此处显示默认图标,可以自定义模板,详见文档
            ,totalRow: true //开启合计行
            , cols: [tableCols]
            ,filter: {
                 items:['column','data','condition','editCondition','excel','clearCache'],
                 cache: true
             }
            , page: true
            ,done: function (res, curr, count) {

                 window.layui.soulTable.render(this);
                 tableDone(this.elem, ins.config.cols[0], local_storage_key);
                 tableDoElse(res, curr, count);//处理其他自定义事件,可在自定义js重写
                 $('div[lay-id=test-table-operate] .layui-table-main').scrollLeft(window.scrollLeft);
            }
        });
//layui表格渲染后,事件需要重新绑定,并记录下筛选信息于localStorage
    function tableDone(elem, col, key){
        elem.next().find('[lay-event="LAYTABLE_COLS"]').click(function(e) {
            setTimeout(function() {
                layui.$(e.currentTarget).find('.layui-form-checkbox').click(function() {
                    var local_config = {};
                    for(var i = 0; i<=col.length-1; i++){
                        if(typeof col[i].field !== 'undefined'){
                            local_config[col[i].field] = col[i].hide ;
                        }
                    }
                    var saveColsConfig = {
                        key: 'local_config',
                        value: local_config
                    };
                    layui.data(key, saveColsConfig);
                })
            }, 50);
        })
    }

    //layuitable reload或第一次加载的时候,根据存储的local_config 确定哪些列是否选中
    function tableSetCol(col, key){
        //参考写法:https://fly.layui.com/jie/50966/#item-1555416248250
        var config_custom= layui.data(key);
        var local_config = config_custom['local_config'] || {};
        if(JSON.stringify(local_config) != '{}'){
            for(var i =0; i<=col.length-1; i++){
                if( typeof col[i].field !== "undefined" ){
                    col[i].hide = local_config[col[i].field];
                }
            }
        }
        return col;
    }
    //监听列固定
    window.layui.form.on('switch(rowDragSwitch)', function(data){
      window.layui.soulTable.suspend('test-table-operate', 'drag', !data.elem.checked)
    });

        
        //监听表格复选框选择
        window.layui.table.on('checkbox(test-table-operate)', function (obj) {
            console.log(obj)
        });
        

        //监听行工具事件
        window.layui.table.on('tool(test-table-operate)', function (obj) { //注:tool 是工具条事件名,test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data //获得当前行数据
                , layEvent = obj.event; //获得 lay-event 对应的值
            
        });
        var activeByType2 = function (type, arg) {
            if (arguments.length === 2) {
                window.active[type] ? window.active[type].call(this, arg) : '';
            } else {
                window.active[type] ? window.active[type].call(this) : '';
            }
        }
        var $ = layui.$;
        window['active'] = {      //表格右边按钮
            getCheckData: function () { //获取选中数据
                var checkStatus = window.layui.table.checkStatus('test-table-operate')
                    , data = checkStatus.data;
                layer.alert(JSON.stringify(data));
            }
            , isadd: function () { //新增
                var checkStatus = window.layui.table.checkStatus('test-table-operate')
                    , data = checkStatus.data;
            }
            , reset: function () { //重置当前页面
             window.layui.form.render('select');
             activeByType2('reload');

            }
            , isdaoru: function () { //导入
                var checkStatus = window.layui.table.checkStatus('test-table-operate')
                    , data = checkStatus.data;


            }
            , isdaochu: function () { //导出
                var checkStatus = window.layui.table.checkStatus('test-table-operate');
     
            }
            , copy: function () { //复制
                var checkStatus = window.layui.table.checkStatus('test-table-operate')
                    , data = checkStatus.data;

            }
            , reload: function () {
             //搜索后横向滚动条不变
             window.layuiTable = $('div[lay-id=test-table-operate] .layui-table-main');
             if(window.layuiTable!=null && window.layuiTable.length>0){
                  window.scrollLeft = window.layuiTable[0].scrollLeft;  
             }
                //执行重载
            window.layui.table.reload('test-table-operate', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    , where: {
                    key:demoReload2.val(),
                    
                }
             });
            }
        };

        //监听排序事件
        window.layui.table.on('sort(test-table-operate)', function (obj) {
            var o = $(this).parent().parent().parent().parent().parent().parent().parent().parent().children('form');
             window.layuiTable = $('div[lay-id=test-table-operate] .layui-table-main');
             if(window.layuiTable!=null && window.layuiTable.length>0){//保证横向滚动排序后不变
                  window.scrollLeft = window.layuiTable[0].scrollLeft;  
             }
            window.layui.table.reload('test-table-operate', {
                initSort: obj //记录初始排序,如果不设的话,将无法标记表头的排序状态。
                , where: { //请求参数(注意:这里面的参数可任意定义,并非下面固定的格式)
                    field: obj.field //排序字段
                    , order: obj.type //排序方式
                }
            });


            //layer.msg('服务端排序。order by '+ obj.field + ' ' + obj.type);
        });
        $('.layui-btn').on('click', function () {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });
        

        window.layui.table.on('radio(test-table-operate)', function (obj) {
            var data = layui.table.checkStatus('test-table-operate').data;
             conId = data[0];
        });
      //重写导出
    function outall() {
        var result=[];
         window.layui.table.exportFile(ins.config.id, result, 'xls');
    }
      //读取表头信息
     function outall2() {
         
         var name = $('div[lay-id=test-table-operate] th:not(.layui-hide)');
         var excelfields = [];
         var excelheader = [];
         for (i = 0; i < name.length; i++) {
             var field = name[i].dataset.field;

             var text = name[i].innerText;
             if (text) {
                 excelheader[i] = text;
                 excelfields[i] = field;
             }

         }

     }
    var  tableDoElse = function (res, curr, count){
        //处理其他自定义事件
    }
    //弹窗回调
    var callbackdata = function () {
        var data = conId;
        return data;
    }
    //监听行
     window.layui.table.on('rowDouble(test-table-operate)', function(obj){

    });
        
</script>

上一篇:网络安全——window对象


下一篇:Browser浏览器对象知识总结