提交 f7786068 编写于 作者: H hjdhnx

加了个没啥用的功能

上级 03c9be83
......@@ -3,15 +3,17 @@
# File : layui.py
# Author: DaShenHan&道长-----先苦后甜,任凭晚风拂柳颜------
# Date : 2022/9/14
import ujson
from flask import Blueprint,request,render_template,jsonify,make_response,redirect
from utils.ua import UA
from utils.web import getParmas,get_interval,layuiBack,verfy_token
from utils.cfg import cfg
from controllers.service import storage_service,rules_service
from utils.system import getHost
from utils.files import getCustonDict,custom_merge
from utils.encode import parseText
from js.rules import getRules,getPys
from js.rules import getRules,getPys,getJxs
from operator import itemgetter, attrgetter
import functools
......@@ -28,6 +30,13 @@ def layui_index(): # put application's code here
return render_template('login.html')
return render_template('layui_list.html')
@layui.route('/jxs')
def layui_jxs(): # put application's code here
# return render_template('layui_index.html')
if not verfy_token():
return render_template('login.html')
return render_template('layui_jxs.html')
@layui.route('/api/list')
def layui_rule_list():
page = int(getParmas('page',1))
......@@ -105,3 +114,37 @@ def layui_rule_list():
new_sites = sites[(page-1)*limit:page*limit]
# print(new_sites)
return layuiBack('获取成功',new_sites,count=len(sites))
@layui.route('/api/jx_list')
def layui_jx_list():
# 拖拽排序教程 https://blog.csdn.net/qq_41829337/article/details/126610406
host = request.host_url # 获取当前访问链接对应的host
page = int(getParmas('page',1))
limit = int(getParmas('limit',10))
new_conf = cfg
lsg = storage_service()
store_conf_dict = lsg.getStoreConfDict()
new_conf.update(store_conf_dict)
ali_token = new_conf.ALI_TOKEN
xr_mode = new_conf.XR_MODE
js0_password = new_conf.JS0_PASSWORD
js_mode = int(new_conf.JS_MODE or 0)
customConfig = getCustonDict(host, ali_token, js0_password)
jxs = getJxs(host=host)
rules = {'list': [{"key": "dr_MXONE", "name": "MXONE(道长)", "type": 1, "api": "{{host}}/vod?{% if js0_password %}pwd={{js0_password}}&{% endif %}rule=MXONE&ext=txt/js/tg/MXONE.js", "searchable": 2, "quickSearch": 0, "filterable": 0},
], 'count': 1}
html = render_template('config.txt', js0_password=js0_password, UA=UA, xr_mode=xr_mode, ISTVB=False, pys=[],
rules=rules, host=host, mode=2, js_mode=js_mode, jxs=jxs, alists=[],
alists_str='', live_url='', config=new_conf)
merged_config = custom_merge(parseText(html), customConfig)
parses = merged_config['parses']
# print(parses)
for i in range(len(parses)):
if not parses[i].get('header'):
parses[i]['header'] = {'User-Agent': 'Mozilla/5.0'}
if isinstance(parses[i].get('header'),dict):
parses[i]['header'] = ujson.dumps(parses[i]['header'],ensure_ascii=False)
if isinstance(parses[i].get('ext'),dict):
parses[i]['ext'] = ujson.dumps(parses[i]['ext'],ensure_ascii=False)
new_parses = parses[(page - 1) * limit:page * limit]
return layuiBack('获取成功', new_parses, count=len(parses))
\ No newline at end of file
3.9.18beta5
\ No newline at end of file
3.9.18beta6
\ No newline at end of file
因为 它太大了无法显示 source diff 。你可以改为 查看blob
/** 自定义字体 **/
/** 这里使用在线字体,如果需要离线包,请看 font/README.md **/
@font-face {
font-family: 'soul-icon'; /* project id 677836 */
src: url('//at.alicdn.com/t/font_677836_jwq362m0tt.eot');
src: url('//at.alicdn.com/t/font_677836_jwq362m0tt.eot?#iefix') format('embedded-opentype'),
url('//at.alicdn.com/t/font_677836_jwq362m0tt.woff2') format('woff2'),
url('//at.alicdn.com/t/font_677836_jwq362m0tt.woff') format('woff'),
url('//at.alicdn.com/t/font_677836_jwq362m0tt.ttf') format('truetype'),
url('//at.alicdn.com/t/font_677836_jwq362m0tt.svg#iconfont') format('svg');
}
.soul-icon {
font-family:"soul-icon" !important;
font-size: 16px;
font-style: normal;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.soul-icon-filter:before { content: "\e60b"; }
.soul-icon-filter-asc:before { content: "\e768"; }
.soul-icon-filter-desc:before { content: "\e767"; }
.soul-icon-asc:before { content: "\e6af"; }
.soul-icon-desc:before { content: "\e6ae"; }
.soul-icon-all-check:before { content: "\e670"; }
.soul-icon-invert-check:before { content: "\e614"; }
.soul-icon-fold:before { content: "\e760"; }
.soul-icon-unfold:before { content: "\e611"; }
.soul-icon-delete:before { content: "\e600"; }
.soul-icon-download:before { content: "\e601"; }
.soul-icon-drop-list:before { content: "\e6a3"; }
.soul-icon-query:before { content: "\e66d"; }
/* 全选*/
.soul-icon-quanxuan:before { content: "\e623"; }
.soul-icon-qingkong:before { content: "\e63e"; }
.soul-icon-autoColumnWidth
:before { content: "\e614"; }
/*最大化*/
.soul-icon-min:before { content: "\e656"; }
.soul-icon-max:before { content: "\e61b"; }
/* 配色方案*/
.layui-red {
color: #FF5722
}
.layui-orange {
color: #FFB800
}
.layui-green {
color: #009688
}
.layui-cyan {
color: #2F4056
}
.layui-blue {
color: #1E9FFF
}
.layui-black {
color: #393D49
}
.layui-gray {
color: #eee
}
.layui-firebrick {
color: firebrick;
}
.layui-deeppink {
color: deeppink;
}
.layui-blueviolet {
color: blueviolet;
}
.soul-condition [class*="layui-col-"] {
margin-top: 10px;
}
/* 表格排序样式*/
.soul-edge {
display: inline-block;
width: 0;
height: 0;
border-width: 6px;
border-style: dashed;
border-color: transparent;
overflow: hidden
}
.soul-table-sort {
width: 10px;
height: 20px;
margin-left: 5px;
cursor: pointer !important;
position: relative;
display: inline-block;
}
.soul-table-sort .soul-edge {
position: absolute;
left: 5px;
border-width: 5px
}
.soul-table-sort .soul-table-sort-asc {
top: 10px;
border-top: none;
border-bottom-style: solid;
border-bottom-color: #b2b2b2
}
.soul-table-sort .soul-table-sort-asc:hover {
border-bottom-color: #666
}
.soul-table-sort .soul-table-sort-desc {
bottom: -2px;
border-bottom: none;
border-top-style: solid;
border-top-color: #b2b2b2
}
.soul-table-sort .soul-table-sort-desc:hover {
border-top-color: #666
}
.soul-table-sort[soul-sort=asc] .soul-table-sort-asc {
border-bottom-color: #000
}
.soul-table-sort[soul-sort=desc] .soul-table-sort-desc {
border-top-color: #000
}
.multiOption {
display: inline-block;
padding: 0 5px;
cursor: pointer;
color: #999;
}
/*表格筛选*/
.soul-table-filter {
line-height: 20px;
color: #b2b2b2;
cursor: pointer;
margin-left: 5px;
}
.soul-table-filter .soul-icon-filter-asc,.soul-table-filter .soul-icon-filter-desc {
display: none;
}
.soul-table-filter[lay-sort="asc"] .soul-icon-filter-asc{
display: block;
color: #000000;
}
.soul-table-filter[lay-sort="asc"] .soul-icon-filter,.soul-table-filter[lay-sort="asc"] .soul-icon-filter-desc{
display: none;
}
.soul-table-filter[lay-sort="desc"] .soul-icon-filter-desc{
display: block;
color: #000000;
}
.soul-table-filter[lay-sort="desc"] .soul-icon-filter,.soul-table-filter[lay-sort="desc"] .soul-icon-filter-asc{
display: none;
}
.soul-table-filter[soul-filter="true"] i {
color: #009688!important;
}
[id^=main-list], [id^=soul-columns], [id^=soul-dropList], [id^=soul-condition], [id^=soul-bf-prefix], [id^=soul-bf-column], [id^=soul-bf-type], [id^=soul-bf-cond2] {
display: inline-block;
position: absolute;
z-index: 2147483647;
background-color: white;
max-height: 200px;
min-width: 160px;
max-width: 300px;
overflow-y: auto;
border: 1px solid #e6e6e6;
border-radius: 5px;
box-shadow: 2px 2px 4px -2px rgba(0,0,0,.2);
}
[id^=main-list] {
max-height: initial;
}
[id^=soul-condition] {
overflow-y: visible;
max-height: initial;
min-width: 285px;
padding: 5px;
}
[id^=soul-condition] .layui-laydate-header {
padding: 4px 70px 5px
}
[id^=soul-condition] hr{
margin: 5px 0;
}
[id^=soul-condition].soul-bf{
min-width: 150px;
}
[id^=soul-filter-list] ul li {
padding: 3px 10px;
cursor: pointer;
}
[id^=soul-filter-list] ul li:hover {
background-color: deepskyblue;
}
[id^=soul-filter-list] i.layui-icon {
display: inline-block;
width: 16px;
}
[id^=soul-dropList] ul {
border: 0;
max-height: 116px;
overflow-y: auto;
}
[id^=soul-dropList] ul li, [id^=soul-filter-list] [id^=soul-columns]>li{
padding: 2px 10px;
}
[id^=soul-dropList] .check {
padding: 5px 10px;
}
.filter-search {
padding: 5px 10px 0 10px;
}
[id^=soul-condition] .layui-inline {
width: 100px;
}
[id^=soul-condition] table.condition-table tr>td {
padding: 0 3px;
}
[id^=soul-condition] table.condition-table tr>td:first-child {
min-width: 60px;
}
[id^=soul-condition] .layui-form-switch {
background-color: #1E9FFF;
border: 1px solid #1E9FFF;
width: 35px;
margin-top: 0px;
}
[id^=soul-condition] .layui-form-switch.layui-form-onswitch {
background-color: #5FB878;
border: 1px solid #5FB878;
}
[id^=soul-condition] .layui-form-switch em {
color: #fff!important;
}
[id^=soul-condition] .layui-form-switch i {
background-color: #fff;
}
[data-type^=date][class$=Condition] {
width: 273px;
}
/*表格筛选*/
[id^=soul-condition]>div{
width: 270px;
}
.soul-condition-title {
text-align: center;
font-weight: bolder;
}
/*底部筛选*/
.soul-bottom-contion {
height: 31px;
/*line-height: 29px;*/
border-top: solid 1px #e6e6e6;
}
.soul-bottom-contion .condition-items {
display: inline-block;
width: calc(100vw - 100px);
height: 30px;
float: left;
overflow: hidden;
white-space: nowrap;
}
.soul-bottom-contion .condition-item>div {
display: inline-block;
height: 28px;
line-height: 28px;
cursor: pointer;
}
.soul-bottom-contion .condition-items .condition-item>div[class^='item-']:hover{
text-decoration: underline;
}
.soul-bottom-contion .condition-items .condition-item{
padding: 0 10px;
margin: 0 2px;
font-weight: bold;
border: solid 1px darkslateblue;
border-radius: 10px;
display: inline-block;
height: 28px;
position: relative;
}
.soul-bottom-contion .editCondtion {
height: 30px;
float: right;
}
.soul-bottom-contion .item-value {
min-width: 20px;
display: inline-block;
}
.soul-bottom-contion .editCondtion a {
border: hidden;
border-left: solid 1px #e6e6e6;
height: 28px;
line-height: 29px;
}
.soul-bottom-contion .condition-items .condition-item .condition-item-close {
position: absolute;
cursor: pointer;
margin-top: -8px;
}
.soul-bottom-contion .condition-items>.condition-item>.condition-item-close {
margin-top: -2px;
}
.soul-bottom-contion .condition-items .condition-item .condition-item-close:hover{
color: red
}
.soul-bottom-contion .condition-items .condition-item .condition-item-close:before {
background: white;
border-radius: 10px;
}
.soul-edit-out {
padding: 10px;
}
[id^=soul-bf] li {
padding: 0px 10px;
height: 22px;
line-height: 22px;
color: #000;
cursor: pointer;
}
[id^=soul-bf] li.soul-bf-selected {
background-color: deepskyblue;
}
[id^=soul-bf] li:hover {
background-color: deepskyblue;
}
.soul-edit-out .tempValue {
height: 25px;
}
.soul-bf-condition-value {
display: inline;
width: 100px;
}
/*子表格*/
.layui-table tbody tr.noHover:hover {
background-color: white;
}
/*编辑筛选*/
.soul-edit-out .layui-form-radio {
margin: 0;
}
.soul-edit-out ul li > div {
display: inline-block;
margin-right: 10px;
height: 25px;
vertical-align: top;
cursor: pointer;
}
.soul-edit-out ul.group {
padding-left: 50px;
}
.soul-edit-out ul.group.line {
border-left: 1px dashed grey;
}
.soul-edit-out ul li {
line-height: 25px;
}
.soul-edit-out table {
display: inline-block;
}
.soul-edit-out table td[data-type='top'] {
width: 12px;
height: 12px;
border-left: dashed 1px grey;
border-bottom: dashed 1px grey;
}
.soul-edit-out table td[data-type='bottom'] {
width: 12px;
height: 12px;
border-left: dashed 1px grey;
}
.soul-edit-out li.last>div>table td[data-type='bottom'] {
border-left: none;
}
.soul-edit-out .layui-form-switch {
background-color: #1E9FFF;
border: 1px solid #1E9FFF;
width: 35px;
margin-top: 0px;
}
.soul-edit-out .layui-form-switch em {
color: #fff!important;
}
.soul-edit-out .layui-form-switch i {
background-color: #fff;
}
.soul-edit-out .layui-form-switch.layui-form-onswitch {
background-color: #5FB878;
border: 1px solid #5FB878;
}
.soul-edit-out .delete-item {
display: none;
}
.soul-edit-out li:hover>.delete-item {
display: inline-block;
}
/* 拖拽相关 */
#column-remove {
position: absolute;
z-index: 2147483647;
}
.layui-table-box.no-left-border td.isDrag, .layui-table-box.no-left-border th.isDrag {
border-left: inherit!important;
}
.soul-drag-bar {
position: absolute;
top: 100px;
z-index: 200;
left: 50%;
font-weight: 900;
color: white;
box-shadow: 0 1px 20px rgba(0,0,0,.15);
text-align: center;
transform: translateX(100vw);
/*transition: transform .3s;*/
}
.soul-drag-bar.active {
transform: translateX(-98px);
}
.soul-drag-bar > div {
display: inline-block;
padding: 10px;
cursor: crosshair;
width: 62px;
background-color: rgba(0, 150, 136, 0.5);
}
.soul-drag-bar > div.active, .soul-drag-bar[data-type='left']>div[data-type='left'], .soul-drag-bar[data-type='right']>div[data-type='right'], .soul-drag-bar[data-type='none']>div[data-type='none'] {
background-color: rgb(0, 150, 136);
}
/* 动画 */
.animated {
-webkit-animation-duration: 1s;
-moz-animation-duration: 1s;
-o-animation-duration: 1s;
animation-duration: 1s;
-webkit-animation-fill-mode: both;
-moz-animation-fill-mode: both;
-o-animation-fill-mode: both;
animation-fill-mode: both;
}
@-moz-keyframes fadeInLeft {
0% {
opacity: 0;
-moz-transform: translateX(-20px);
}
100% {
opacity: 1;
-moz-transform: translateX(0);
}
}
@-o-keyframes fadeInLeft {
0% {
opacity: 0;
-o-transform: translateX(-20px);
}
100% {
opacity: 1;
-o-transform: translateX(0);
}
}
@keyframes fadeInLeft {
0% {
opacity: 0;
transform: translateX(-20px);
}
100% {
opacity: 1;
transform: translateX(0);
}
}
.animated.fadeInLeft {
-webkit-animation-name: fadeInLeft;
-moz-animation-name: fadeInLeft;
-o-animation-name: fadeInLeft;
animation-name: fadeInLeft;
}
@-webkit-keyframes fadeOutLeft {
0% {
opacity: 1;
-webkit-transform: translateX(0);
}
100% {
opacity: 0;
-webkit-transform: translateX(-20px);
}
}
@-moz-keyframes fadeOutLeft {
0% {
opacity: 1;
-moz-transform: translateX(0);
}
100% {
opacity: 0;
-moz-transform: translateX(-20px);
}
}
@-o-keyframes fadeOutLeft {
0% {
opacity: 1;
-o-transform: translateX(0);
}
100% {
opacity: 0;
-o-transform: translateX(-20px);
}
}
@keyframes fadeOutLeft {
0% {
opacity: 1;
transform: translateX(0);
}
100% {
opacity: 0;
transform: translateX(-20px);
}
}
.animated.fadeOutLeft {
-webkit-animation-name: fadeOutLeft;
-moz-animation-name: fadeOutLeft;
-o-animation-name: fadeOutLeft;
animation-name: fadeOutLeft;
}
@-webkit-keyframes fadeInRight {
0% {
opacity: 0;
-webkit-transform: translateX(20px);
}
100% {
opacity: 1;
-webkit-transform: translateX(0);
}
}
@-moz-keyframes fadeInRight {
0% {
opacity: 0;
-moz-transform: translateX(20px);
}
100% {
opacity: 1;
-moz-transform: translateX(0);
}
}
@-o-keyframes fadeInRight {
0% {
opacity: 0;
-o-transform: translateX(20px);
}
100% {
opacity: 1;
-o-transform: translateX(0);
}
}
@keyframes fadeInRight {
0% {
opacity: 0;
transform: translateX(20px);
}
100% {
opacity: 1;
transform: translateX(0);
}
}
.animated.fadeInRight {
-webkit-animation-name: fadeInRight;
-moz-animation-name: fadeInRight;
-o-animation-name: fadeInRight;
animation-name: fadeInRight;
}
@-webkit-keyframes fadeInUp {
0% {
opacity: 0;
-webkit-transform: translateY(20px);
}
100% {
opacity: 1;
-webkit-transform: translateY(0);
}
}
@-moz-keyframes fadeInUp {
0% {
opacity: 0;
-moz-transform: translateY(20px);
}
100% {
opacity: 1;
-moz-transform: translateY(0);
}
}
@-o-keyframes fadeInUp {
0% {
opacity: 0;
-o-transform: translateY(20px);
}
100% {
opacity: 1;
-o-transform: translateY(0);
}
}
@keyframes fadeInUp {
0% {
opacity: 0;
transform: translateY(20px);
}
100% {
opacity: 1;
transform: translateY(0);
}
}
.animated.fadeInUp {
-webkit-animation-name: fadeInUp;
-moz-animation-name: fadeInUp;
-o-animation-name: fadeInUp;
animation-name: fadeInUp;
}
@-webkit-keyframes fadeOutDown {
0% {
opacity: 1;
-webkit-transform: translateY(0);
}
100% {
opacity: 0;
-webkit-transform: translateY(20px);
}
}
@-moz-keyframes fadeOutDown {
0% {
opacity: 1;
-moz-transform: translateY(0);
}
100% {
opacity: 0;
-moz-transform: translateY(20px);
}
}
@-o-keyframes fadeOutDown {
0% {
opacity: 1;
-o-transform: translateY(0);
}
100% {
opacity: 0;
-o-transform: translateY(20px);
}
}
@keyframes fadeOutDown {
0% {
opacity: 1;
transform: translateY(0);
}
100% {
opacity: 0;
transform: translateY(20px);
}
}
.animated.fadeOutDown {
-webkit-animation-name: fadeOutDown;
-moz-animation-name: fadeOutDown;
-o-animation-name: fadeOutDown;
animation-name: fadeOutDown;
}
#soul-table-contextmenu-wrapper {
width: 0;
}
.soul-table-contextmenu {
position: absolute;
z-index: 2147483647;
list-style: none;
margin: 0;
padding: 0;
border: 1px solid #ebeef5;
box-shadow: 2px 2px 4px -2px rgba(0,0,0,.2);
background: white;
}
.soul-table-contextmenu li {
line-height: 26px;
padding: 0 30px;
cursor: pointer;
word-break: keep-all;
}
.soul-table-contextmenu li:hover {
background: #c5c5c5;
}
.soul-table-contextmenu li i.prefixIcon{
position: absolute;
left: 8px;
}
.soul-table-contextmenu li i.endIcon{
position: absolute;
right: 8px;
}
/*拖拽相关*/
.layui-table-sort-invalid {
width: 10px;
height: 20px;
margin-left: 5px;
cursor: pointer!important;
}
.layui-table-sort-invalid .layui-table-sort-asc {
top: 3px;
border-top: none;
border-bottom-style: solid;
border-bottom-color: #b2b2b2;
}
.layui-table-sort-invalid .layui-edge {
position: absolute;
left: 5px;
border-width: 5px;
}
.layui-table-sort-invalid .layui-table-sort-desc {
bottom: 5px;
border-bottom: none;
border-top-style: solid;
border-top-color: #b2b2b2;
}
.layui-table-sort-invalid .layui-edge {
position: absolute;
left: 5px;
border-width: 5px;
}
.noselect {
-webkit-touch-callout: none; /* iOS Safari */
-webkit-user-select: none; /* Chrome/Safari/Opera */
-khtml-user-select: none; /* Konqueror */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* Internet Explorer/Edge */
user-select: none; /* Non-prefixed version, currently */
}
/* 固定列滚动 */
.soul-fixed-scroll::-webkit-scrollbar{
display: none
}
.soul-fixed-scroll{
overflow-y: auto!important;
-ms-overflow-style:none;
overflow:-moz-scrollbars-none;
}
/**
*
* @name: 表格增强插件
* @author: yelog
* @link: https://github.com/yelog/layui-soul-table
* @license: MIT
* @version: v1.6.4
*/
layui.define(['table', 'tableFilter', 'tableChild', 'tableMerge'], function (exports) {
var tableFilter = layui.tableFilter,
tableChild = layui.tableChild,
tableMerge = layui.tableMerge,
$ = layui.$,
table = layui.table,
HIDE = 'layui-hide',
tables = {},
originCols = {},
defaultConfig = { // 默认配置开关
fixTotal: false, // 修复合计行固定列问题
drag: true, // 列拖动
rowDrag: false, // 行拖动
autoColumnWidth: true, // 自动列宽
contextmenu: false, // 右键菜单
fixResize: true, // 修改有固定列的拖动列宽的位置为左边线
overflow: false, // 自定义内容超出样式
fixFixedScroll: true, // 固定列支持鼠标滚轮滚动
filter: false // 筛选及记忆相关
},
_BODY = $('body'),
_DOC = $(document);
// 封装方法
var mod = {
render: function (myTable) {
// 记录表格配置,方便直接通过 tableId 调用方法
tables[myTable.id] = myTable
var curConfig = $.extend({}, defaultConfig, myTable);
if (curConfig.filter && curConfig.filter.cache) {
var storeKey = location.pathname + location.hash + myTable.id;
var colsStr = this.deepStringify(myTable.cols);
// 记录表格列的原始配置
if (!originCols[myTable.id]) { // 只在第一次 render 时生效
originCols[myTable.id] = this.deepClone(myTable.cols)
var curTableSession = localStorage.getItem(storeKey);
if (curTableSession && colsStr === localStorage.getItem('origin' + storeKey)) {
this.updateCols(myTable, this.deepParse(curTableSession));
} else {
localStorage.setItem('origin' + storeKey, colsStr)
localStorage.removeItem(storeKey)
}
}
} else {
// 如果没有开启记忆,则清除
this.clearCache(myTable);
}
tableFilter.render(myTable);
tableChild.render(myTable);
tableMerge.render(myTable);
// 初始化暂停配置
this.suspendConfig[myTable.id] = {
drag: false,
rowDrag: false
}
// 修复合计栏固定列问题
if (curConfig.fixTotal) {
this.fixTotal(myTable)
}
if (curConfig.drag) {
this.drag(myTable, curConfig.drag);
}
if (curConfig.rowDrag) {
this.rowDrag(myTable, curConfig.rowDrag)
}
if (curConfig.autoColumnWidth) {
this.autoColumnWidth(myTable, curConfig.autoColumnWidth)
}
this.contextmenu(myTable, curConfig.contextmenu);
if (curConfig.fixResize) {
this.fixResizeRightFixed(myTable);
}
if (curConfig.overflow) {
this.overflow(myTable, curConfig.overflow);
}
if (curConfig.fixFixedScroll) {
this.fixFixedScroll(myTable);
}
}
, config: function (configObj) {
if (typeof configObj === 'object') {
$.extend(true, defaultConfig, configObj);
}
}
, updateCols: function (myTable, cols) {
var i, j, lastKeyMap = {}, columnKey, newCols = [], col = [],
$table = $(myTable.elem),
$tableBox = $table.next().children('.layui-table-box'),
$fixedHead = $tableBox.children('.layui-table-fixed').children('.layui-table-header').children('table'),
$tableHead = $.merge($tableBox.children('.layui-table-header').children('table'), $fixedHead),
$noFixedHead = $tableBox.children('.layui-table-header').children('table'),
$fixedBody = $tableBox.children('.layui-table-fixed').children('.layui-table-body').children('table'),
$noFixedBody = $tableBox.children('.layui-table-body').children('table'),
$tableBody = $.merge($tableBox.children('.layui-table-body').children('table'), $fixedBody);
for (i = 0; i < myTable.cols.length; i++) {
for (j = 0; j < myTable.cols[i].length; j++) {
myTable.cols[i][j]['oldPos'] = i + '-' + j
lastKeyMap[myTable.cols[i][j].key] = myTable.cols[i][j]
}
}
for (i = 0; i < cols.length; i++) {
col = []
for (j = 0; j < cols[i].length; j++) {
columnKey = myTable.index + '-' + cols[i][j].key;
// 同步列宽
if (cols[i][j].width && lastKeyMap[cols[i][j].key] !== cols[i][j].width) {
this.getCssRule(myTable, columnKey, function (item) {
item.style.width = (cols[i][j].width ? cols[i][j].width : 0) + 'px'
})
}
// 同步隐藏
if (lastKeyMap[cols[i][j].key].hide !== cols[i][j].hide) {
$tableHead.find('th[data-key="' + columnKey + '"]')[cols[i][j].hide ? 'addClass' : 'removeClass']('layui-hide')
$tableBody.find('td[data-key="' + columnKey + '"]')[cols[i][j].hide ? 'addClass' : 'removeClass']('layui-hide')
}
// 同步顺序
if (lastKeyMap[cols[i][j].key].oldPos !== (i + '-' + j) || lastKeyMap[cols[i][j].key].fixed !== cols[i][j].fixed) {
if (cols[i][j].fixed !== lastKeyMap[cols[i][j].key].fixed) {
myTable.cols = cols;
table.reload(myTable.id)
return;
}
}
lastKeyMap[cols[i][j].key].fixed = cols[i][j].fixed;
lastKeyMap[cols[i][j].key].width = cols[i][j].width;
lastKeyMap[cols[i][j].key].hide = cols[i][j].hide;
col.push(lastKeyMap[cols[i][j].key])
}
newCols.push(col)
}
$noFixedHead.children().children('tr').each(function () {
innerHandler(this, 'th')
})
$noFixedBody.children().children('tr').each(function () {
innerHandler(this, 'td')
})
function innerHandler(_this, domName) {
for (i = 0; i < cols.length; i++) {
for (j = 0; j < cols[i].length; j++) {
columnKey = myTable.index + '-' + cols[i][j].key;
var curKey = $(_this).children(domName + ':eq(' + j + ')').attr('data-key');
if (curKey !== columnKey) {
$(_this).children(domName + ':eq(' + j + ')').before($(_this).children(domName + '[data-key="' + columnKey + '"]'))
if (cols[i][j].fixed) {
var $curRow = (domName === 'th' ? $fixedHead : $fixedBody).children().children(domName === 'th' ? 'tr' : 'tr[data-index="' + $(_this).attr('data-index') + '"]')
$curRow.children(domName + '[data-key="' + curKey + '"]').before($curRow.children(domName + '[data-key="' + columnKey + '"]'))
}
}
}
}
}
myTable.cols = newCols;
table.resize(myTable.id)
}
/**
* excel表格导出
* @param myTable
* @param curExcel
*/
, export: function (myTable, curExcel) {
tableFilter.export(myTable.config || myTable, curExcel);
}
, getCssRule: function (that, key, callback) {
var style = that.elem.next().find('style')[0]
, sheet = style.sheet || style.styleSheet || {}
, rules = sheet.cssRules || sheet.rules;
layui.each(rules, function (i, item) {
if (item.selectorText === ('.laytable-cell-' + key)) {
return callback(item), true;
}
});
}
, autoColumnWidth: function (myTable, autoColumnWidthConfig) {
var _this = this;
if (typeof myTable === 'object') {
innerColumnWidth(_this, myTable)
} else if (typeof myTable === 'string') {
innerColumnWidth(_this, tables[myTable])
} else if (typeof myTable === 'undefined') {
layui.each(tables, function () {
innerColumnWidth(_this, this)
});
}
function innerColumnWidth(_this, myTable) {
var $table = $(myTable.elem),
th = $table.next().children('.layui-table-box').children('.layui-table-header').children('table').children('thead').children('tr').children('th'),
fixTh = $table.next().children('.layui-table-box').children('.layui-table-fixed').children('.layui-table-header').children('table').children('thead').children('tr').children('th'),
$tableBodytr = $table.next().children('.layui-table-box').children('.layui-table-body').children('table').children('tbody').children('tr'),
$totalTr = $table.next().children('.layui-table-total').find('tr');
String.prototype.width = function (font) {
var f = font || _BODY.css('font'),
o = $('<div>' + this + '</div>')
.css({
'position': 'absolute',
'float': 'left',
'white-space': 'nowrap',
'visibility': 'hidden',
'font': f
})
.appendTo(_BODY),
w = o.width();
o.remove();
return w;
}
if (typeof autoColumnWidthConfig === 'undefined' || typeof autoColumnWidthConfig.dblclick === 'undefined' || autoColumnWidthConfig.dblclick) {
th.add(fixTh).on('dblclick', function (e) {
var othis = $(this),
pLeft = e.clientX - othis.offset().left;
handleColumnWidth(myTable, othis, othis.parents('.layui-table-fixed-r').length > 0 ? pLeft <= 10 : othis.width() - pLeft <= 10);
})
}
// 初始化表格后,自动调整所有列宽
if (autoColumnWidthConfig && autoColumnWidthConfig.init) {
th.add(fixTh).each(function (e) {
var colKey = $(this).attr('data-key').split('-')
if (myTable.cols[colKey[1]][colKey[2]].autoWidth !== false && (!Array.isArray(autoColumnWidthConfig.init) || autoColumnWidthConfig.init.indexOf($(this).attr('data-field')) !== -1)) {
handleColumnWidth(myTable, $(this), true);
}
})
}
function handleColumnWidth(myTable, othis, isHandle) {
var key = othis.data('key')
, keyArray = key.split('-')
, curKey = keyArray.length === 3 ? keyArray[1] + '-' + keyArray[2] : ''
if (othis.attr('colspan') > 1 || othis.data('unresize')) {
return;
}
if (isHandle) {
var maxWidth = othis.text().width(othis.css('font')) + 21, font = othis.css('font');
$tableBodytr.children('td[data-key="' + key + '"]').each(function (index, elem) {
var curWidth = 0
if ($(this).children().children() && $(this).children().children().length > 0) {
curWidth += $(this).children().html().width(font)
} else {
curWidth = $(this).text().width(font);
}
// var curWidth = $(this).text().width(font);
if (maxWidth < curWidth) {
maxWidth = curWidth
}
})
if ($totalTr.length > 0) {
var curWidth = $totalTr.children('td[data-key="' + key + '"]').text().width(font)
if (maxWidth < curWidth) {
maxWidth = curWidth
}
}
maxWidth += 32;
_this.getCssRule(myTable, key, function (item) {
item.style.width = maxWidth + 'px'
});
for (var i = 0; i < myTable.cols.length; i++) {
for (var j = 0; j < myTable.cols[i].length; j++) {
if (myTable.cols[i][j].key === curKey) {
myTable.cols[i][j].width = maxWidth;
break;
}
}
}
}
}
}
}
/**
* 左右拖拽调整列顺序、向上拖隐藏列
* @param myTable
*/
, drag: function (myTable, dragConfig) {
if (myTable.cols.length > 1) {
// 如果是复杂表头,则自动禁用拖动效果
return;
}
var _this = this,
$table = $(myTable.elem),
$tableBox = $table.next().children('.layui-table-box'),
$tableHead = $.merge($tableBox.children('.layui-table-header').children('table'), $tableBox.children('.layui-table-fixed').children('.layui-table-header').children('table')),
$fixedBody = $tableBox.children('.layui-table-fixed').children('.layui-table-body').children('table'),
$noFixedBody = $tableBox.children('.layui-table-body').children('table'),
$tableBody = $.merge($tableBox.children('.layui-table-body').children('table'), $fixedBody),
$totalTable = $table.next().children('.layui-table-total').children('table'),
$fixedTotalTable = $table.next().children('.layui-table-total').children('table.layui-table-total-fixed'),
$noFixedTotalTable = $table.next().children('.layui-table-total').children('table:eq(0)'),
tableId = myTable.id,
isSimple = dragConfig === 'simple' || (dragConfig && dragConfig.type === 'simple'), // 是否为简易拖拽
toolbar = dragConfig && dragConfig.toolbar, // 是否开启工具栏
isDragging = false, isStart = false;
if (!$tableHead.attr('drag')) {
$tableHead.attr('drag', true);
if (toolbar) {
$tableBox.append('<div class="soul-drag-bar"><div data-type="left">左固定</div><div data-type="none">不固定</div><div data-type="right">右固定</div></div>')
var $dragBar = $tableBox.children('.soul-drag-bar');
$dragBar.children('div').on('mouseenter', function () {
$(this).addClass('active')
}).on('mouseleave', function () {
$(this).removeClass('active')
})
}
$tableHead.find('th').each(function () {
var $this = $(this),
field = $this.data('field'),
key = $this.data('key');
if (!key) {
return;
}
var keyArray = key.split('-'),
curColumn = myTable.cols[keyArray[1]][keyArray[2]],
curKey = keyArray[1] + '-' + keyArray[2],
isInFixed = $this.parents('.layui-table-fixed').length > 0;
// 绑定鼠标按下事件
$(this).find('span:first,.laytable-cell-checkbox')
.css('cursor', 'move')
.on('mousedown', function (e) {
// 暂停或者非鼠标左键都不执行
if (_this.suspendConfig[tableId].drag || e.button !== 0) {
return;
}
e.preventDefault();
var $cloneHead = $this.clone().css('visibility', 'hidden'),
originLeft = $this.position().left,
originTop = $this.offset().top,
disX = e.clientX - originLeft, // 鼠标距离被移动元素左侧的距离
color = $this.parents('tr:eq(0)').css("background-color"),
width = $this.width(), moveDistince = 0,
$that = $(this),
isFixed = curColumn.fixed;
isStart = true;
//区分click、drag事件
// 阻止文本选中
_DOC.bind("selectstart", function () {
return false;
});
// 移动事件
_BODY.on('mousemove', function (e) {
if (isStart && $cloneHead) {
$tableBox.removeClass('no-left-border');
if (!isDragging) {
if (toolbar) {
$dragBar.attr('data-type', isFixed || 'none')
$dragBar.addClass('active')
}
$this.after($cloneHead);
$this.addClass('isDrag').css({
'position': 'absolute',
'z-index': 1,
'border-left': '1px solid #e6e6e6',
'background-color': color,
'width': width + 1
});
if (isSimple) {
//设置蒙板
} else {
(isInFixed ? $fixedBody : $tableBody).find('td[data-key="' + key + '"]').each(function () {
$(this).after($(this).clone().css('visibility', 'hidden').attr('data-clone', ''));
$(this).addClass('isDrag').css({
'position': 'absolute',
'z-index': 1,
'border-left': '1px solid #e6e6e6',
'background-color': $(this).css('background-color'),
'width': width + 1
});
})
if ($totalTable.length > 0) {
(isInFixed ? $fixedTotalTable : $totalTable).find('td[data-key="' + key + '"]').each(function () {
$(this).after($(this).clone().css('visibility', 'hidden').attr('data-clone', ''));
$(this).addClass('isDrag').css({
'position': 'absolute',
'z-index': 1,
'background-color': $(this).parents('tr:eq(0)').css('background-color'),
'width': width + 1
});
})
}
}
}
isDragging = true;
var x, y, i, j, tempCols,
left = e.clientX - disX, // 计算当前被移动列左侧位置应该哪里
$leftTh = $cloneHead.prev().prev(),
hasLeftTh = $leftTh.length > 0,
leftKey = hasLeftTh ? $leftTh.data('key').split('-') : [],
$rightTh = $cloneHead.next().hasClass('layui-table-patch') ? [] : $cloneHead.next(),
hasRightTh = $rightTh.length > 0,
rightKey = hasRightTh ? $rightTh.data('key').split('-') : [],
leftMove = hasLeftTh && ($cloneHead.position().left - left > $leftTh.width() / 2.0),
rightMove = hasRightTh && (left - $cloneHead.position().left > $rightTh.width() / 2.0);
moveDistince = Math.abs($cloneHead.position().left - left); //记录移动距离
// 移动到左右两端、checbox/radio 固定列等停止移动
if ($cloneHead.position().left - left > 0
? !hasLeftTh || !!isFixed !== !!myTable.cols[leftKey[1]][leftKey[2]].fixed
: !hasRightTh || !!isFixed !== !!myTable.cols[rightKey[1]][rightKey[2]].fixed) {
$this.css('left', $cloneHead.position().left);
$tableBody.find('td[data-key="' + key + '"][data-clone]').each(function (e) {
$(this).prev().css('left', $cloneHead.position().left);
})
if ($totalTable.length > 0) {
$totalTable.find('td[data-key="' + key + '"][data-clone]').each(function (e) {
$(this).prev().css('left', $cloneHead.position().left);
})
}
$tableBox.addClass('no-left-border');
return;
}
$this.css('left', left);
if (leftMove) {
$cloneHead.after($leftTh);
// 更新隐藏列顺序
$('#soul-columns' + tableId + '>li[data-value="' + field + '"]').after($('#soul-columns' + tableId + '>li[data-value="' + field + '"]').prev())
// 更新配置信息
for (i = 0; i < myTable.cols.length; i++) {
for (j = 0; j < myTable.cols[i].length; j++) {
if (myTable.cols[i][j].key === curKey) {
x = i;
y = j;
break;
}
}
if (typeof x !== 'undefined' && typeof y !== 'undefined') {
break;
}
}
tempCols = myTable.cols[x][y - 1];
myTable.cols[x][y - 1] = myTable.cols[x][y];
myTable.cols[x][y] = tempCols;
_this.fixTableRemember(myTable);
} else if (rightMove) {
$cloneHead.prev().before($rightTh);
// 更新隐藏列顺序
$('#soul-columns' + tableId + '>li[data-value="' + field + '"]').before($('#soul-columns' + tableId + '>li[data-value="' + field + '"]').next())
// 更新配置信息
for (i = 0; i < myTable.cols.length; i++) {
for (j = 0; j < myTable.cols[i].length; j++) {
if (myTable.cols[i][j].key === curKey) {
x = i;
y = j;
break;
}
}
if (typeof x !== 'undefined' && typeof y !== 'undefined') {
break;
}
}
tempCols = myTable.cols[x][y + 1];
myTable.cols[x][y + 1] = myTable.cols[x][y];
myTable.cols[x][y] = tempCols;
_this.fixTableRemember(myTable);
}
$tableBody.find('td[data-key="' + key + '"][data-clone]').each(function () {
$(this).prev().css('left', left);
if (leftMove) {
if ($(this).prev().prev().length !== 0) {
$(this).after($(this).prev().prev());
}
} else if (rightMove) {
if ($(this).next().length !== 0) {
$(this).prev().before($(this).next());
}
}
})
if ($totalTable.length > 0) {
$totalTable.find('td[data-key="' + key + '"][data-clone]').each(function () {
$(this).prev().css('left', left);
if (leftMove) {
if ($(this).prev().prev().length !== 0) {
$(this).after($(this).prev().prev());
}
} else if (rightMove) {
if ($(this).next().length !== 0) {
$(this).prev().before($(this).next());
}
}
})
}
/* 拖动隐藏列 */
if (e.clientY - originTop < -15) {
if ($('#column-remove').length === 0) {
_BODY.append('<i id="column-remove" class="layui-red layui-icon layui-icon-delete"></i>')
}
$('#column-remove').css({
top: e.clientY - $('#column-remove').height() / 2,
left: e.clientX - $('#column-remove').width() / 2,
'font-size': (originTop - e.clientY) + 'px'
})
$('#column-remove').show();
} else {
$('#column-remove').hide();
}
}
}).on('mouseup', function () {
_DOC.unbind("selectstart");
_BODY.off('mousemove').off('mouseup')
if (isStart && $cloneHead) {
isStart = false;
if (isDragging) {
if (curColumn.type !== 'checkbox') {
$that.on('click', function (e) {
e.stopPropagation();
});
}
isDragging = false;
$tableBox.removeClass('no-left-border')
$this.removeClass('isDrag').css({
'position': 'relative',
'z-index': 'inherit',
'left': 'inherit',
'border-left': 'inherit',
'width': 'inherit',
'background-color': 'inherit'
});
$this.next().remove();
var prefKey = $this.prev().data('key');
if (isFixed) {
var $noFixedTh = $tableBox.children('.layui-table-header').children('table').find('th[data-key="' + key + '"]');
if (prefKey) {
$noFixedTh.parent().children('th[data-key="' + prefKey + '"]').after($noFixedTh)
} else {
if (isFixed === 'right') {
if ($this.siblings().length > 0) {
$tableBox.children('.layui-table-header').children('table').find('th[data-key="' + $this.next().data('key') + '"]').prev().after($noFixedTh);
}
} else {
$noFixedTh.parent().prepend('<th class="layui-hide"></th>');
$noFixedTh.parent().children('th:first').after($noFixedTh);
$noFixedTh.parent().children('th:first').remove();
}
}
}
if (isSimple) {
$tableBody.find('td[data-key="' + key + '"]').each(function () {
if (prefKey) {
$(this).parent().children('td[data-key="' + prefKey + '"]').after($(this))
} else {
if (isFixed === 'right') {
if ($this.siblings().length > 0) {
var $preTd = $(this).parent().children('td[data-key="' + $this.next().data('key') + '"]').prev();
if ($preTd.length > 0) {
$preTd.after($(this));
} else {
$(this).parent().prepend('<td class="layui-hide"></td>');
$(this).parent().children('td:first').after($(this));
$(this).parent().children('td:first').remove();
}
}
} else {
$(this).parent().prepend('<td class="layui-hide"></td>');
$(this).parent().children('td:first').after($(this));
$(this).parent().children('td:first').remove();
}
}
});
if ($totalTable.length > 0) {
$totalTable.find('td[data-key="' + key + '"]').each(function () {
if (prefKey) {
$(this).parent().children('td[data-key="' + prefKey + '"]').after($(this))
} else {
if (isFixed === 'right') {
var $preTd = $(this).parent().children('td[data-key="' + $this.next().data('key') + '"]').prev();
if ($preTd.length > 0) {
$preTd.after($(this));
} else {
$(this).parent().prepend('<td class="layui-hide"></td>');
$(this).parent().children('td:first').after($(this));
$(this).parent().children('td:first').remove();
}
} else {
$(this).parent().prepend('<td class="layui-hide"></td>');
$(this).parent().children('td:first').after($(this));
$(this).parent().children('td:first').remove();
}
}
});
}
} else if (isInFixed) {
$noFixedBody.find('td[data-key="' + key + '"]').each(function () {
if (prefKey) {
$(this).parent().children('td[data-key="' + prefKey + '"]').after($(this))
} else {
if (isFixed === 'right') {
if ($this.siblings().length > 0) {
var $preTd = $(this).parent().children('td[data-key="' + $this.next().data('key') + '"]').prev();
if ($preTd.length > 0) {
$preTd.after($(this));
} else {
$(this).parent().prepend('<td class="layui-hide"></td>');
$(this).parent().children('td:first').after($(this));
$(this).parent().children('td:first').remove();
}
}
} else {
$(this).parent().prepend('<td class="layui-hide"></td>');
$(this).parent().children('td:first').after($(this));
$(this).parent().children('td:first').remove();
}
}
});
$fixedBody.find('td[data-key="' + key + '"][data-clone]').each(function () {
$(this).prev().removeClass('isDrag').css({
'position': 'relative',
'z-index': 'inherit',
'left': 'inherit',
'border-left': 'inherit',
'width': 'inherit',
'background-color': 'inherit'
});
$(this).remove();
});
if ($totalTable.length > 0) {
$noFixedTotalTable.find('td[data-key="' + key + '"]').each(function () {
if (prefKey) {
$(this).parent().children('td[data-key="' + prefKey + '"]').after($(this))
} else {
if (isFixed === 'right') {
var $preTd = $(this).parent().children('td[data-key="' + $this.next().data('key') + '"]').prev();
if ($preTd.length > 0) {
$preTd.after($(this));
} else {
$(this).parent().prepend('<td class="layui-hide"></td>');
$(this).parent().children('td:first').after($(this));
$(this).parent().children('td:first').remove();
}
} else {
$(this).parent().prepend('<td class="layui-hide"></td>');
$(this).parent().children('td:first').after($(this));
$(this).parent().children('td:first').remove();
}
}
});
$fixedTotalTable.find('td[data-key="' + key + '"][data-clone]').each(function () {
$(this).prev().removeClass('isDrag').css({
'position': 'relative',
'z-index': 'inherit',
'left': 'inherit',
'width': 'inherit',
'background-color': 'inherit'
});
$(this).remove();
});
}
} else {
$tableBody.find('td[data-key="' + key + '"][data-clone]').each(function () {
$(this).prev().removeClass('isDrag').css({
'position': 'relative',
'z-index': 'inherit',
'left': 'inherit',
'width': 'inherit',
'background-color': 'inherit'
});
$(this).remove();
});
if ($totalTable.length > 0) {
$totalTable.find('td[data-key="' + key + '"][data-clone]').each(function () {
$(this).prev().removeClass('isDrag').css({
'position': 'relative',
'z-index': 'inherit',
'left': 'inherit',
'width': 'inherit',
'background-color': 'inherit'
});
$(this).remove();
});
}
}
$cloneHead = null;
// 处理 toolbar 事件
if (toolbar) {
if ($dragBar.children('.active').length > 0 && $dragBar.children('.active').attr('data-type') !== $dragBar.attr('data-type')) {
var targetFix = $dragBar.children('.active').attr('data-type'),
i, j, curPos, targetPos;
for (i = 0; i < myTable.cols.length; i++) {
for (j = 0; j < myTable.cols[i].length; j++) {
if (targetFix === 'right' || (targetFix === 'none' && $dragBar.attr('data-type') === 'right')) {
if (typeof targetPos === 'undefined') {
if (myTable.cols[i][j].fixed === 'right') {
targetPos = {x: i, y: j};
} else if (j === myTable.cols[i].length - 1) {
targetPos = {x: i, y: j + 1};
}
}
} else {
if (typeof targetPos === 'undefined' && (!myTable.cols[i][j].fixed || myTable.cols[i][j].fixed === 'right')) {
targetPos = {x: i, y: j};
}
}
if (myTable.cols[i][j].key === curKey) {
curPos = {x: i, y: j};
}
}
}
curColumn['fixed'] = targetFix === 'none' ? false : targetFix;
if (curPos.y !== targetPos.y) {
myTable.cols[curPos.x].splice(curPos.y, 1);
if (curPos.y < targetPos.y) {
targetPos.y -= 1
}
myTable.cols[targetPos.x].splice(targetPos.y, 0, curColumn)
_this.fixTableRemember(myTable);
}
table.reload(tableId)
}
$dragBar.removeClass('active')
}
} else {
$that.unbind('click');
}
if ($('#column-remove').is(':visible')) {
$tableHead.find('thead>tr>th[data-key=' + key + ']').addClass(HIDE);
$tableBody.find('tbody>tr>td[data-key="' + key + '"]').addClass(HIDE);
$totalTable.find('tbody>tr>td[data-key="' + key + '"]').addClass(HIDE);
// 同步配置
curColumn['hide'] = true
_this.fixTableRemember(myTable);
// 更新下拉隐藏
$('#soul-columns' + tableId).find('li[data-value="' + field + '"]>input').prop('checked', false);
tableFilter.resize(myTable)
}
$('#column-remove').hide();
}
})
});
})
}
},
rowDrag: function (myTable, rowDragConfig) {
var _this = this,
$table = $(myTable.elem),
$tableBox = $table.next().children('.layui-table-box'),
$fixedBody = $tableBox.children('.layui-table-fixed').children('.layui-table-body').children('table'),
$noFixedBody = $tableBox.children('.layui-table-body').children('table'),
$tableBody = $.merge($tableBox.children('.layui-table-body').children('table'), $fixedBody),
tableId = myTable.id,
isDragging = false,
trigger = rowDragConfig.trigger || 'row',
syncNumber = rowDragConfig.numbers !== false,
numberColumnKey = null, numberStart = 0,
$trs = trigger === 'row' ? $tableBody.children('tbody').children('tr') : $tableBody.find(trigger),
i, j;
if (trigger !== 'row') {
$tableBody.find(trigger).css('cursor', 'move')
}
for (i = 0; i < myTable.cols.length; i++) {
for (j = 0; j < myTable.cols[i].length; j++) {
if (myTable.cols[i][j].type === 'numbers') {
numberColumnKey = myTable.index + '-' + i + '-' + j;
numberStart = parseInt($noFixedBody.find('td[data-key="' + numberColumnKey + '"]:first').text());
break;
}
}
}
$trs.on('mousedown', function (e) {
// 被暂停 或者 不是鼠标左键 则取消拖拽效果
if (_this.suspendConfig[tableId].rowDrag || e.button !== 0) {
return;
}
var $this = trigger === 'row' ? $(this) : $(this).parents('tr:eq(0)'),
index = parseInt($this.data('index')), // 被拖拽行索引
$bodyTr = $noFixedBody.children('tbody').children('tr[data-index=' + index + ']'), // 被拖拽行(非固定列)
$cloneTr = $bodyTr.clone().css('visibility', 'hidden'), // 占位行
$FixBodyTr = $fixedBody.children('tbody').children('tr[data-index=' + index + ']'), // 被拖拽行(固定列)
bodyScrollTop = $tableBox.children('.layui-table-body').scrollTop(), // 记录当前滚动条位置
originTop = $this.position().top, // 被拖拽行当前位置
disY = e.clientY - originTop; // 鼠标距离被拖拽行上侧的距离
_BODY.on('mousemove', function (e) {
// 刚被拖动
if (!isDragging) {
isDragging = true;
// 设置鼠标样式
// $table.next().find('style').append('.layui-table-view .layui-table td{cursor: move;}.layui-table tr{transition: none}')
var style = $table.next().find('style')[0],
sheet = style.sheet || style.styleSheet || {};
_this.addCSSRule(sheet, '.layui-table-view .layui-table td', 'cursor: move')
_this.addCSSRule(sheet, '.layui-table tr', 'transition: none')
$tableBox.addClass('noselect'); // 禁止选中文本
$bodyTr.after($cloneTr);
$bodyTr.css({
'position': 'absolute',
'z-index': 1
})
$FixBodyTr.each(function () {
$(this).after($(this).clone().css('visibility', 'hidden'))
$(this).css({
'position': 'absolute',
'z-index': 102
})
})
}
var top = e.clientY - disY + ($tableBox.children('.layui-table-body').scrollTop() - bodyScrollTop), // 计算当前被移动行top位置应该哪里
trTop = $cloneTr.position().top, //当前行所在位置
$UpTr = $bodyTr.prev(),
hasUpTr = $UpTr.length > 0,
$downTr = $cloneTr.next(),
hasDownTr = $downTr.length > 0,
upMove = hasUpTr && (trTop - top > $UpTr.height() / 2.0),
downMove = hasDownTr && (top - trTop > $downTr.height() / 2.0);
if (trTop - top > 0 ? !hasUpTr : !hasDownTr) {
$bodyTr.css('top', trTop);
$FixBodyTr.each(function () {
$(this).css('top', trTop);
})
return;
}
$bodyTr.css('top', top);
$FixBodyTr.each(function () {
$(this).css('top', top);
})
if (upMove) {
updateDataIndex($bodyTr, -1)
$cloneTr.after(updateDataIndex($UpTr, 1));
$FixBodyTr.each(function () {
updateDataIndex($(this), -1)
$(this).next().after(updateDataIndex($(this).prev(), 1));
})
} else if (downMove) {
updateDataIndex($bodyTr, 1).before(updateDataIndex($downTr, -1))
$FixBodyTr.each(function () {
updateDataIndex($(this), 1);
$(this).before(updateDataIndex($(this).next().next(), -1));
})
}
// 同步 data-index
function updateDataIndex($el, diff) {
var tempIndex = parseInt($el.data('index')) + diff;
$el.data('index', tempIndex);
$el.attr('data-index', tempIndex);
return $el
}
}).on('mouseup', function (e) {
_BODY.off('mousemove').off('mouseup');
if (isDragging) {
isDragging = false;
$tableBox.removeClass('noselect'); // 取消禁止选中文本
$bodyTr.css({'position': 'inherit', 'z-index': 'inherit'});
$bodyTr.next().remove();
$FixBodyTr.each(function () {
$(this).css({'position': 'inherit', 'z-index': 'inherit'});
$(this).next().remove()
})
// 恢复样式
var style = $table.next().find('style')[0],
sheet = style.sheet || style.styleSheet || {},
rules = sheet.cssRules || sheet.rules;
layui.each(rules, function (i, item) {
if (item.selectorText === ('.layui-table-view .layui-table td')) {
item.style.cursor = 'default';
}
});
var newIndex = $this.index(),
cache = table.cache[tableId];
if (newIndex !== index) { // 有位置变动
// 如果 before 返回 false,则还原拖拽
if (typeof rowDragConfig.before === 'function'
&& rowDragConfig.before.call(myTable, {
row: cache[index],
newIndex: newIndex,
oldIndex: index,
cache: cache
}) === false) {
// 同步 data-index
function updateDataIndex($el, setIndex) {
$el.data('index', setIndex);
$el.attr('data-index', setIndex);
return $el
}
// 还原位置和索引
if (newIndex < index) {
for (i = newIndex; i < index; i++) {
updateDataIndex($noFixedBody.find('tr[data-index="'+(i+1)+'"]'), i)
updateDataIndex($fixedBody.find('tr[data-index="'+(i+1)+'"]'), i)
}
updateDataIndex($bodyTr, index)
$noFixedBody.find('tr[data-index="'+(index - 1)+'"]').after($bodyTr)
$FixBodyTr.each(function () {
updateDataIndex($(this), index)
$(this).parent().children('tr[data-index="'+(index - 1)+'"]').after($(this))
})
} else {
for (i = newIndex; i > index; i--) {
updateDataIndex($noFixedBody.find('tr[data-index="'+(i-1)+'"]'), i)
updateDataIndex($fixedBody.find('tr[data-index="'+(i-1)+'"]'), i)
}
updateDataIndex($bodyTr, index)
$noFixedBody.find('tr[data-index="'+(index + 1)+'"]').before($bodyTr)
$FixBodyTr.each(function () {
updateDataIndex($(this), index)
$(this).parent().children('tr[data-index="'+(index + 1)+'"]').before($(this))
})
}
return;
}
var row = cache.splice(index, 1)[0];
cache.splice(newIndex, 0, row);
if (numberColumnKey && syncNumber) {
// 进行序号重排
var sortedIndexs = [newIndex, index].sort()
for (i = sortedIndexs[0]; i <= sortedIndexs[1]; i++) {
var curIndex = numberStart + i;
$fixedBody.find('td[data-key="' + numberColumnKey + '"]:eq(' + i + ')').children().html(curIndex)
$noFixedBody.find('td[data-key="' + numberColumnKey + '"]:eq(' + i + ')').children().html(curIndex)
cache[i][table.config.indexName] = curIndex - 1
}
}
if (typeof rowDragConfig.done === 'function') {
rowDragConfig.done.call(myTable, {
row: row,
newIndex: newIndex,
oldIndex: index,
cache: cache
})
}
}
}
})
})
},
fixTableRemember: function (myTable, dict) {
if (typeof myTable.filter === 'undefined' ? (defaultConfig.filter && defaultConfig.filter.cache) : myTable.filter.cache) {
if (dict && dict.rule) {
var curKey = dict.rule.selectorText.split('-')[3] + '-' + dict.rule.selectorText.split('-')[4];
for (var i = 0; i < myTable.cols.length; i++) {
for (var j = 0; j < myTable.cols[i].length; j++) {
if (myTable.cols[i][j].key === curKey) {
myTable.cols[i][j].width = dict.rule.style.width.replace('px', '');
break;
}
}
}
}
var storeKey = location.pathname + location.hash + myTable.id;
localStorage.setItem(storeKey, this.deepStringify(myTable.cols))
}
},
clearCache: function (myTable) {
if (!myTable) {
return;
}
var tableId;
if (typeof myTable === 'object') {
if (typeof myTable.config !== 'undefined') {
tableId = myTable.config.id
} else {
tableId = myTable.id
}
} else {
tableId = myTable
}
localStorage.removeItem(location.pathname + location.hash + tableId)
if (originCols[tableId]) {
this.updateCols(tables[tableId], this.deepClone(originCols[tableId]))
}
},
overflow: function (myTable, overflowConfig) {
var options = {};
if (typeof overflowConfig === 'string') {
options = {
type: overflowConfig
}
} else if (typeof overflowConfig === 'object') {
options = overflowConfig
} else {
return;
}
var $table = $(myTable.elem),
layHeader = $table.next().find('.layui-table-header'),
layBody = $table.next().find('.layui-table-body'),
layTotal = $table.next().find('.layui-table-total'),
tooltipIndex,
hoverTime = options.hoverTime || 0,
tooltipTimeOut,
color = options.color || 'white',
bgColor = options.bgColor || 'black',
minWidth = options.minWidth || 300,
maxWidth = options.maxWidth || 300;
if (options.type === 'tips') {
layBody.off('mouseenter', 'td').off('mouseleave', 'td').on('mouseenter', 'td', function () {
var _this = this;
tooltipTimeOut = setTimeout(function () {
toopTip.call(_this)
}, hoverTime)
}).on('mouseleave', 'td', function () {
toopTip.call(this, 'hide')
})
if (options.header) {
layHeader.off('mouseenter', 'th').off('mouseleave', 'th').on('mouseenter', 'th', function () {
var _this = this;
tooltipTimeOut = setTimeout(function () {
toopTip.call(_this)
}, hoverTime)
}).on('mouseleave', 'th', function () {
toopTip.call(this, 'hide')
})
}
if (options.total) {
layTotal.off('mouseenter', 'td').off('mouseleave', 'td').on('mouseenter', 'td', function () {
var _this = this;
tooltipTimeOut = setTimeout(function () {
toopTip.call(_this)
}, hoverTime)
}).on('mouseleave', 'td', function () {
toopTip.call(this, 'hide')
})
}
function toopTip(hide) {
clearTimeout(tooltipTimeOut);
var othis = $(this)
, elemCell = othis.children('.layui-table-cell')
, width = elemCell.outerWidth()
, layerWidth = width < minWidth ? minWidth : width > maxWidth ? maxWidth : width;
if (othis.data('off')) return;
if (hide) {
layer.close(tooltipIndex)
} else if (elemCell.prop('scrollWidth') > width) {
tooltipIndex = layer.tips('<span style="color: ' + color + '">' + $(this).text() + '</span>', this, {
tips: [1, bgColor],
maxWidth: layerWidth,
time: 0
});
}
}
} else if (options.type === 'title') {
layBody.off('mouseenter', 'td').on('mouseenter', 'td', function () {
var othis = $(this)
, elemCell = othis.children('.layui-table-cell');
if (othis.data('off')) return;
if (elemCell.prop('scrollWidth') > elemCell.outerWidth()) {
elemCell.attr('title', $(this).text())
}
})
if (options.header) {
layHeader.off('mouseenter', 'th').on('mouseenter', 'th', function () {
var othis = $(this)
, elemCell = othis.children('.layui-table-cell');
if (othis.data('off')) return;
if (elemCell.prop('scrollWidth') > elemCell.outerWidth()) {
elemCell.attr('title', $(this).text())
}
})
}
if (options.total) {
layTotal.off('mouseenter', 'td').on('mouseenter', 'td', function () {
var othis = $(this)
, elemCell = othis.children('.layui-table-cell');
if (othis.data('off')) return;
if (elemCell.prop('scrollWidth') > elemCell.outerWidth()) {
elemCell.attr('title', $(this).text())
}
})
}
}
},
// 右键菜单配置
contextmenu: function (myTable, contextmenuConfig) {
var $table = $(myTable.elem),
$tableBox = $table.next().children('.layui-table-box'),
$tableHead = $.merge($tableBox.children('.layui-table-header').children('table'), $tableBox.children('.layui-table-fixed').children('.layui-table-header').children('table')),
$fixedBody = $tableBox.children('.layui-table-fixed').children('.layui-table-body').children('table'),
$tableBody = $.merge($tableBox.children('.layui-table-body').children('table'), $fixedBody),
$totalTable = $table.next().children('.layui-table-total').children('table'),
tableId = myTable.id,
header = contextmenuConfig ? contextmenuConfig.header : '',
body = contextmenuConfig ? contextmenuConfig.body : '',
total = contextmenuConfig ? contextmenuConfig.total : '',
options = {
header: {box: $tableHead, tag: 'th', opts: header, cols: {}},
body: {box: $tableBody, tag: 'td', opts: body, cols: {}, isBody: true},
total: {box: $totalTable, tag: 'td', opts: total, cols: {}}
},
hasColsContext = false;
for (var i = 0; i < myTable.cols.length; i++) {
for (var j = 0; j < myTable.cols[i].length; j++) {
if (myTable.cols[i][j].contextmenu) {
hasColsContext = true
options.header.cols[myTable.cols[i][j].key] = myTable.cols[i][j].contextmenu.header
options.body.cols[myTable.cols[i][j].key] = myTable.cols[i][j].contextmenu.body
options.total.cols[myTable.cols[i][j].key] = myTable.cols[i][j].contextmenu.total
}
}
}
if (!contextmenuConfig && !hasColsContext) {
return;
}
for (var name in options) {
(function (name) {
options[name].box.find(options[name].tag).on('contextmenu', function (e) {
$('#soul-table-contextmenu-wrapper').remove();
_BODY.append('<div id="soul-table-contextmenu-wrapper"></div>');
$('#soul-table-contextmenu-wrapper').on('click', function (e) {
e.stopPropagation()
})
var curColsOpts = options[name].cols[$(this).data('key').substr($(this).data('key').indexOf('-') + 1)];
if (curColsOpts === false) {
return false
} else if (curColsOpts && curColsOpts.length > 0) {
genePanel($('#soul-table-contextmenu-wrapper'), e.pageX, e.pageY, curColsOpts, $(this), options[name].box, options[name].tag, options[name].isBody);
return false
} else if (options[name].opts === false) {
return false
} else if (options[name].opts && options[name].opts.length > 0) {
genePanel($('#soul-table-contextmenu-wrapper'), e.pageX, e.pageY, options[name].opts, $(this), options[name].box, options[name].tag, options[name].isBody);
return false
}
})
})(name)
}
_BODY.on('click', function () {
$('#soul-table-contextmenu-wrapper').remove();
})
function genePanel($parent, left, top, options, $this, box, tag, isBody) {
var html = [], i;
html.push('<ul class="soul-table-contextmenu">');
for (i = 0; i < options.length; i++) {
html.push('<li data-index="' + i + '" class="' + (options[i].children && options[i].children.length > 0 ? 'contextmenu-children' : '') + '">')
if (options[i].icon) {
html.push('<i class="prefixIcon ' + options[i].icon + '" />')
} else {
html.push('<i class="prefixIcon" />')
}
html.push(options[i].name)
if (options[i].children && options[i].children.length > 0) {
html.push('<i class="endIcon layui-icon layui-icon-right" />')
}
html.push('</li>')
}
html.push('</ul>');
$parent.append(html.join(''));
var $curPanel = $parent.children().last();
if (top + $curPanel.outerHeight() > _BODY.prop('scrollHeight')) {
top = top - $curPanel.outerHeight()
if (top < 0) {
top = 0
}
}
if ($parent.parent().data('direction') === 'left' && ($parent.offset().left - $curPanel.outerWidth()) > 0) {
left = -$curPanel.outerWidth();
$curPanel.data('direction', 'left')
} else if (left + $curPanel.outerWidth() + $parent.offset().left > _BODY.prop('scrollWidth')) {
left = left - $curPanel.outerWidth() - $parent.outerWidth()
if (left + $parent.offset().left < 0) {
left = -$parent.offset().left
}
$curPanel.data('direction', 'left')
}
$curPanel.css({
top: top + 'px',
left: left + 'px'
})
for (i = 0; i < options.length; i++) {
if (typeof options[i].click === "function") {
(function (i) {
$parent.children('.soul-table-contextmenu:last').children('li[data-index="' + i + '"]').on('click', function () {
var index = $this.parents('tr:eq(0)').data('index'),
tr = box.find('tr[data-index="' + index + '"]'),
row = layui.table.cache[tableId][index];
options[i].click.call(myTable, {
cell: $this,
elem: tag === 'th' ? $this : isBody ? box.children('tbody').children('tr[data-index="' + index + '"]').children('[data-key="' + $this.data('key') + '"]') : box.find('[data-key="' + $this.data('key') + '"]'),
trElem: box.children('tbody').children('tr[data-index="' + index + '"]'),
text: $this.text(),
field: $this.data('field'),
del: !isBody ? '' : function () {
table.cache[tableId][index] = [];
tr.remove();
table.resize(tableId);
},
update: !isBody ? '' : function (fields) {
fields = fields || {};
layui.each(fields, function (key, value) {
if (key in row) {
var templet, td = tr.children('td[data-field="' + key + '"]');
row[key] = value;
table.eachCols(tableId, function (i, item2) {
if (item2.field == key && item2.templet) {
templet = item2.templet;
}
});
td.children('.layui-table-cell').html(function () {
return templet ? function () {
return typeof templet === 'function'
? templet(row)
: layui.laytpl($(templet).html() || value).render(row)
}() : value;
}());
td.data('content', value);
}
});
},
row: isBody ? row : {},
})
$('#soul-table-contextmenu-wrapper').remove();
})
})(i)
}
}
$parent.children('.soul-table-contextmenu:last').children('li').on('mouseenter', function (e) {
e.stopPropagation()
$(this).siblings('.contextmenu-children').children('ul').remove();
if ($(this).hasClass('contextmenu-children')) {
genePanel($(this), $(this).outerWidth(), $(this).position().top, options[$(this).data('index')].children, $this, box, tag, isBody)
}
})
}
},
fixTotal: function (myTable) {
var $table = $(myTable.elem),
$total = $table.next().children('.layui-table-total'),
style = $table.next().find('style')[0],
sheet = style.sheet || style.styleSheet || {};
if ($total.length > 0) {
var $tableBox = $table.next().children('.layui-table-box'),
$fixedLeft = $tableBox.children('.layui-table-fixed-l').children('.layui-table-body').children('table').children('tbody').children('tr:eq(0)').children('td'),
$fixedRight = $tableBox.children('.layui-table-fixed-r').children('.layui-table-body').children('table').children('tbody').children('tr:eq(0)').children('td'),
html = [];
$total.children('.layui-table-total-fixed').remove()
if ($fixedLeft.length > 0) {
this.addCSSRule(sheet, '.layui-table-total-fixed-l .layui-table-patch', 'display: none')
$table.next().css('position', 'relative');
html.push('<table style="position: absolute;background-color: #fff;left: 0;top: ' + ($total.position().top + 1) + 'px" cellspacing="0" cellpadding="0" border="0" class="layui-table layui-table-total-fixed layui-table-total-fixed-l"><tbody><tr>');
$fixedLeft.each(function () {
if ($(this).data('key')) {
html.push($total.children('table:eq(0)').find('[data-key="' + $(this).data('key') + '"]').prop("outerHTML"))
}
})
html.push('</tr></tbody></table>');
$total.append(html.join(''))
}
if ($fixedRight.length > 0) {
this.addCSSRule(sheet, '.layui-table-total-fixed-r td:first-child', 'border-left:1px solid #e6e6e6')
this.addCSSRule(sheet, '.layui-table-total-fixed-r td:last-child', 'border-left: none')
$table.next().css('position', 'relative');
html = [];
html.push('<table style="position: absolute;background-color: #fff;right: 0;top: ' + ($total.position().top + 1) + 'px" cellspacing="0" cellpadding="0" border="0" class="layui-table layui-table-total-fixed layui-table-total-fixed-r"><tbody><tr>');
$fixedRight.each(function () {
html.push($total.children('table:eq(0)').find('[data-key="' + $(this).data('key') + '"]').prop("outerHTML"))
})
html.push('</tr></tbody></table>')
$total.append(html.join(''))
}
}
},
fixResizeRightFixed: function (myTable) {
var _this = this,
$table = $(myTable.elem),
$tableBox = $table.next().children('.layui-table-box'),
$fixedHead = $tableBox.children('.layui-table-fixed-r').children('.layui-table-header').children('table'),
dict = {}, resizing, ELEM_SORT = 'layui-table-sort',
ELEM_NO_SORT = 'layui-table-sort-invalid';
if ($fixedHead.length > 0) {
$fixedHead.find('th').off('mousemove').on('mousemove', function (e) {
var othis = $(this)
, oLeft = othis.offset().left
, pLeft = e.clientX - oLeft;
if (othis.data('unresize') || dict.resizeStart) {
return;
}
if (othis.width() - pLeft <= 10) {
_BODY.css('cursor', 'initial')
}
dict.allowResize = pLeft <= 10; //是否处于拖拽允许区域
_BODY.css('cursor', (dict.allowResize ? 'col-resize' : ''));
}).off('mousedown').on('mousedown', function (e) {
var othis = $(this);
if (dict.allowResize) {
othis.find('.' + ELEM_SORT).removeClass(ELEM_SORT).addClass(ELEM_NO_SORT)
var key = othis.data('key');
e.preventDefault();
dict.resizeStart = true; //开始拖拽
dict.offset = [e.clientX, e.clientY]; //记录初始坐标
_this.getCssRule(myTable, key, function (item) {
var width = item.style.width || othis.outerWidth();
dict.rule = item;
dict.ruleWidth = parseFloat(width);
dict.othis = othis;
dict.minWidth = othis.data('minwidth') || myTable.cellMinWidth;
});
}
});
//拖拽中
_DOC.on('mousemove', function (e) {
if (dict.resizeStart) {
layui.soulTable.fixTableRemember(myTable, dict)
e.preventDefault();
if (dict.rule) {
var setWidth = dict.ruleWidth - e.clientX + dict.offset[0];
if (setWidth < dict.minWidth) setWidth = dict.minWidth;
dict.rule.style.width = setWidth + 'px';
}
resizing = 1
}
}).on('mouseup', function (e) {
if (dict.resizeStart) {
setTimeout(function () {
dict.othis.find('.' + ELEM_NO_SORT).removeClass(ELEM_NO_SORT).addClass(ELEM_SORT)
_BODY.css('cursor', '');
dict = {};
_this.scrollPatch(myTable);
}, 30)
}
if (resizing === 2) {
resizing = null;
}
});
}
},
fixFixedScroll: function (myTable) {
var $table = $(myTable.elem),
layFixed = $table.next().children('.layui-table-box').children('.layui-table-fixed'),
layMain = $table.next().children('.layui-table-box').children('.layui-table-main');
layFixed.on('mouseenter', function () {
$(this).children('.layui-table-body').addClass('soul-fixed-scroll').on('scroll', function () {
var scrollTop = $(this).scrollTop()
// layFixed.children('.layui-table-body[class!="soul-fixed-scroll"]').scrollTop(scrollTop);
layMain.scrollTop(scrollTop);
})
}).on('mouseleave', function () {
$(this).children('.layui-table-body').removeClass('soul-fixed-scroll').off('scroll');
})
},
scrollPatch: function (myTable) {
var $table = $(myTable.elem),
layHeader = $table.next().children('.layui-table-box').children('.layui-table-header'),
layTotal = $table.next().children('.layui-table-total'),
layMain = $table.next().children('.layui-table-box').children('.layui-table-main'),
layFixed = $table.next().children('.layui-table-box').children('.layui-table-fixed'),
layFixRight = $table.next().children('.layui-table-box').children('.layui-table-fixed-r'),
layMainTable = layMain.children('table'),
scollWidth = layMain.width() - layMain.prop('clientWidth'),
scollHeight = layMain.height() - layMain.prop('clientHeight'),
outWidth = layMainTable.outerWidth() - layMain.width() //表格内容器的超出宽度
//添加补丁
, addPatch = function (elem) {
if (scollWidth && scollHeight) {
elem = elem.eq(0);
if (!elem.find('.layui-table-patch')[0]) {
var patchElem = $('<th class="layui-table-patch"><div class="layui-table-cell"></div></th>'); //补丁元素
patchElem.find('div').css({
width: scollWidth
});
elem.find('tr').append(patchElem);
}
} else {
elem.find('.layui-table-patch').remove();
}
}
addPatch(layHeader);
addPatch(layTotal);
//固定列区域高度
var mainHeight = layMain.height()
, fixHeight = mainHeight - scollHeight;
layFixed.find('.layui-table-body').css('height', layMainTable.height() >= fixHeight ? fixHeight : 'auto');
//表格宽度小于容器宽度时,隐藏固定列
layFixRight[outWidth > 0 ? 'removeClass' : 'addClass'](HIDE);
//操作栏
layFixRight.css('right', scollWidth - 1);
},
/**
* 一键粘贴
* @param {String} text [需要 copy 的属性,默认是 innerText,主要用途例如赋值 a 标签上的 href 链接]
*
* range + selection
*
* 1.创建一个 range
* 2.把内容放入 range
* 3.把 range 放入 selection
*
* 注意:参数 attr 不能是自定义属性
* 注意:对于 user-select: none 的元素无效
* 注意:当 id 为 false 且 attr 不会空,会直接复制 attr 的内容
*/
copy: function (text) {
var target;
if (text) {
target = document.createElement('div');
target.id = 'tempTarget';
target.style.opacity = '0';
target.innerText = text;
document.body.appendChild(target);
} else {
target = document.querySelector('#' + id);
}
try {
var range = document.createRange();
range.selectNode(target);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
document.execCommand('copy');
window.getSelection().removeAllRanges();
} catch (e) {
console.log('复制失败')
}
if (text) {
// remove temp target
target.parentElement.removeChild(target);
}
},
addCSSRule: function (sheet, selector, rules, index) {
if ('insertRule' in sheet) {
sheet.insertRule(selector + '{' + rules + '}', index)
} else if ('addRule' in sheet) {
sheet.addRule(selector, rules, index)
}
},
deepStringify: function (obj) {
var JSON_SERIALIZE_FIX = {
PREFIX: "[[JSON_FUN_PREFIX_",
SUFFIX: "_JSON_FUN_SUFFIX]]"
};
return JSON.stringify(obj, function (key, value) {
if (typeof value === 'function') {
return JSON_SERIALIZE_FIX.PREFIX + value.toString() + JSON_SERIALIZE_FIX.SUFFIX;
}
return value;
});
},
deepParse: function (str) {
var JSON_SERIALIZE_FIX = {
PREFIX: "[[JSON_FUN_PREFIX_",
SUFFIX: "_JSON_FUN_SUFFIX]]"
};
return JSON.parse(str, function (key, value) {
if (typeof value === 'string' &&
value.indexOf(JSON_SERIALIZE_FIX.SUFFIX) > 0 && value.indexOf(JSON_SERIALIZE_FIX.PREFIX) === 0) {
return eval("(" + value.replace(JSON_SERIALIZE_FIX.PREFIX, "").replace(JSON_SERIALIZE_FIX.SUFFIX, "") + ")");
}
return value;
}) || {};
},
clearFilter: function (myTable) {
tableFilter.clearFilter(myTable);
},
cache: tableFilter.cache,
// 深度克隆-不丢失方法
deepClone: function (obj) {
var newObj = Array.isArray(obj) ? [] : {}
if (obj && typeof obj === "object") {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
newObj[key] = (obj && typeof obj[key] === 'object') ? this.deepClone(obj[key]) : obj[key];
}
}
}
return newObj
},
clearOriginCols: function (tableId) {
if (tableId) {
delete originCols[tableId]
} else {
originCols = {}
}
},
suspendConfig: {},
/**
* 暂停某个特性
* @param tableId
* @param type 暂停的类型,支持 'drag' 'rowDrag'
* @param value true/false
*/
suspend: function (tableId, type, value) {
this.suspendConfig[tableId][type] = value
}
}
// 输出
exports('soulTable', mod);
});
/**
*
* @name: 表格增强插件-独立版本
* @author: yelog
* @link: https://github.com/yelog/layui-soul-table
* @license: MIT
* @version: v1.6.4
*/
layui.define(['table'], function (exports) {
var $ = layui.$,
table = layui.table,
HIDE = 'layui-hide',
tables = {},
originCols = {},
defaultConfig = { // 默认配置开关
fixTotal: false, // 修复合计行固定列问题
drag: true, // 列拖动
rowDrag: false, // 行拖动
autoColumnWidth: true, // 自动列宽
contextmenu: false, // 右键菜单
fixResize: true, // 修改有固定列的拖动列宽的位置为左边线
overflow: false, // 自定义内容超出样式
fixFixedScroll: true, // 固定列支持鼠标滚轮滚动
filter: false // 筛选及记忆相关
},
_BODY = $('body'),
_DOC = $(document);
// 封装方法
var mod = {
render: function (myTable) {
// 记录表格配置,方便直接通过 tableId 调用方法
tables[myTable.id] = myTable
var curConfig = $.extend({}, defaultConfig, myTable);
if (curConfig.filter && curConfig.filter.cache) {
var storeKey = location.pathname + location.hash + myTable.id;
var colsStr = this.deepStringify(myTable.cols);
// 记录表格列的原始配置
if (!originCols[myTable.id]) { // 只在第一次 render 时生效
originCols[myTable.id] = this.deepClone(myTable.cols)
var curTableSession = localStorage.getItem(storeKey);
if (curTableSession && colsStr === localStorage.getItem('origin' + storeKey)) {
this.updateCols(myTable, this.deepParse(curTableSession));
} else {
localStorage.setItem('origin' + storeKey, colsStr)
localStorage.removeItem(storeKey)
}
}
} else {
// 如果没有开启记忆,则清除
this.clearCache(myTable);
}
// 初始化暂停配置
this.suspendConfig[myTable.id] = {
drag: false,
rowDrag: false
}
// 修复合计栏固定列问题
if (curConfig.fixTotal) {
this.fixTotal(myTable)
}
if (curConfig.drag) {
this.drag(myTable, curConfig.drag);
}
if (curConfig.rowDrag) {
this.rowDrag(myTable, curConfig.rowDrag)
}
if (curConfig.autoColumnWidth) {
this.autoColumnWidth(myTable, curConfig.autoColumnWidth)
}
this.contextmenu(myTable, curConfig.contextmenu);
if (curConfig.fixResize) {
this.fixResizeRightFixed(myTable);
}
if (curConfig.overflow) {
this.overflow(myTable, curConfig.overflow);
}
if (curConfig.fixFixedScroll) {
this.fixFixedScroll(myTable);
}
}
, config: function (configObj) {
if (typeof configObj === 'object') {
$.extend(true, defaultConfig, configObj);
}
}
, updateCols: function (myTable, cols) {
var i, j, lastKeyMap = {}, columnKey, newCols = [], col = [],
$table = $(myTable.elem),
$tableBox = $table.next().children('.layui-table-box'),
$fixedHead = $tableBox.children('.layui-table-fixed').children('.layui-table-header').children('table'),
$tableHead = $.merge($tableBox.children('.layui-table-header').children('table'), $fixedHead),
$noFixedHead = $tableBox.children('.layui-table-header').children('table'),
$fixedBody = $tableBox.children('.layui-table-fixed').children('.layui-table-body').children('table'),
$noFixedBody = $tableBox.children('.layui-table-body').children('table'),
$tableBody = $.merge($tableBox.children('.layui-table-body').children('table'), $fixedBody);
for (i = 0; i < myTable.cols.length; i++) {
for (j = 0; j < myTable.cols[i].length; j++) {
myTable.cols[i][j]['oldPos'] = i + '-' + j
lastKeyMap[myTable.cols[i][j].key] = myTable.cols[i][j]
}
}
for (i = 0; i < cols.length; i++) {
col = []
for (j = 0; j < cols[i].length; j++) {
columnKey = myTable.index + '-' + cols[i][j].key;
// 同步列宽
if (cols[i][j].width && lastKeyMap[cols[i][j].key] !== cols[i][j].width) {
this.getCssRule(myTable, columnKey, function (item) {
item.style.width = (cols[i][j].width ? cols[i][j].width : 0) + 'px'
})
}
// 同步隐藏
if (lastKeyMap[cols[i][j].key].hide !== cols[i][j].hide) {
$tableHead.find('th[data-key="' + columnKey + '"]')[cols[i][j].hide ? 'addClass' : 'removeClass']('layui-hide')
$tableBody.find('td[data-key="' + columnKey + '"]')[cols[i][j].hide ? 'addClass' : 'removeClass']('layui-hide')
}
// 同步顺序
if (lastKeyMap[cols[i][j].key].oldPos !== (i + '-' + j) || lastKeyMap[cols[i][j].key].fixed !== cols[i][j].fixed) {
if (cols[i][j].fixed !== lastKeyMap[cols[i][j].key].fixed) {
myTable.cols = cols;
table.reload(myTable.id)
return;
}
}
lastKeyMap[cols[i][j].key].fixed = cols[i][j].fixed;
lastKeyMap[cols[i][j].key].width = cols[i][j].width;
lastKeyMap[cols[i][j].key].hide = cols[i][j].hide;
col.push(lastKeyMap[cols[i][j].key])
}
newCols.push(col)
}
$noFixedHead.children().children('tr').each(function () {
innerHandler(this, 'th')
})
$noFixedBody.children().children('tr').each(function () {
innerHandler(this, 'td')
})
function innerHandler(_this, domName) {
for (i = 0; i < cols.length; i++) {
for (j = 0; j < cols[i].length; j++) {
columnKey = myTable.index + '-' + cols[i][j].key;
var curKey = $(_this).children(domName + ':eq(' + j + ')').attr('data-key');
if (curKey !== columnKey) {
$(_this).children(domName + ':eq(' + j + ')').before($(_this).children(domName + '[data-key="' + columnKey + '"]'))
if (cols[i][j].fixed) {
var $curRow = (domName === 'th' ? $fixedHead : $fixedBody).children().children(domName === 'th' ? 'tr' : 'tr[data-index="' + $(_this).attr('data-index') + '"]')
$curRow.children(domName + '[data-key="' + curKey + '"]').before($curRow.children(domName + '[data-key="' + columnKey + '"]'))
}
}
}
}
}
myTable.cols = newCols;
table.resize(myTable.id)
}
, getCssRule: function (that, key, callback) {
var style = that.elem.next().find('style')[0]
, sheet = style.sheet || style.styleSheet || {}
, rules = sheet.cssRules || sheet.rules;
layui.each(rules, function (i, item) {
if (item.selectorText === ('.laytable-cell-' + key)) {
return callback(item), true;
}
});
}
, autoColumnWidth: function (myTable, autoColumnWidthConfig) {
var _this = this;
if (typeof myTable === 'object') {
innerColumnWidth(_this, myTable)
} else if (typeof myTable === 'string') {
innerColumnWidth(_this, tables[myTable])
} else if (typeof myTable === 'undefined') {
layui.each(tables, function () {
innerColumnWidth(_this, this)
});
}
function innerColumnWidth(_this, myTable) {
var $table = $(myTable.elem),
th = $table.next().children('.layui-table-box').children('.layui-table-header').children('table').children('thead').children('tr').children('th'),
fixTh = $table.next().children('.layui-table-box').children('.layui-table-fixed').children('.layui-table-header').children('table').children('thead').children('tr').children('th'),
$tableBodytr = $table.next().children('.layui-table-box').children('.layui-table-body').children('table').children('tbody').children('tr'),
$totalTr = $table.next().children('.layui-table-total').find('tr');
String.prototype.width = function (font) {
var f = font || _BODY.css('font'),
o = $('<div>' + this + '</div>')
.css({
'position': 'absolute',
'float': 'left',
'white-space': 'nowrap',
'visibility': 'hidden',
'font': f
})
.appendTo(_BODY),
w = o.width();
o.remove();
return w;
}
if (typeof autoColumnWidthConfig === 'undefined' || typeof autoColumnWidthConfig.dblclick === 'undefined' || autoColumnWidthConfig.dblclick) {
th.add(fixTh).on('dblclick', function (e) {
var othis = $(this),
pLeft = e.clientX - othis.offset().left;
handleColumnWidth(myTable, othis, othis.parents('.layui-table-fixed-r').length > 0 ? pLeft <= 10 : othis.width() - pLeft <= 10);
})
}
// 初始化表格后,自动调整所有列宽
if (autoColumnWidthConfig && autoColumnWidthConfig.init) {
th.add(fixTh).each(function (e) {
var colKey = $(this).attr('data-key').split('-')
if (myTable.cols[colKey[1]][colKey[2]].autoWidth !== false && (!Array.isArray(autoColumnWidthConfig.init) || autoColumnWidthConfig.init.indexOf($(this).attr('data-field')) !== -1)) {
handleColumnWidth(myTable, $(this), true);
}
})
}
function handleColumnWidth(myTable, othis, isHandle) {
var key = othis.data('key')
, keyArray = key.split('-')
, curKey = keyArray.length === 3 ? keyArray[1] + '-' + keyArray[2] : ''
if (othis.attr('colspan') > 1 || othis.data('unresize')) {
return;
}
if (isHandle) {
var maxWidth = othis.text().width(othis.css('font')) + 21, font = othis.css('font');
$tableBodytr.children('td[data-key="' + key + '"]').each(function (index, elem) {
var curWidth = 0
if ($(this).children().children() && $(this).children().children().length > 0) {
curWidth += $(this).children().html().width(font)
} else {
curWidth = $(this).text().width(font);
}
// var curWidth = $(this).text().width(font);
if (maxWidth < curWidth) {
maxWidth = curWidth
}
})
if ($totalTr.length > 0) {
var curWidth = $totalTr.children('td[data-key="' + key + '"]').text().width(font)
if (maxWidth < curWidth) {
maxWidth = curWidth
}
}
maxWidth += 32;
_this.getCssRule(myTable, key, function (item) {
item.style.width = maxWidth + 'px'
});
for (var i = 0; i < myTable.cols.length; i++) {
for (var j = 0; j < myTable.cols[i].length; j++) {
if (myTable.cols[i][j].key === curKey) {
myTable.cols[i][j].width = maxWidth;
break;
}
}
}
}
}
}
}
/**
* 左右拖拽调整列顺序、向上拖隐藏列
* @param myTable
*/
, drag: function (myTable, dragConfig) {
if (myTable.cols.length > 1) {
// 如果是复杂表头,则自动禁用拖动效果
return;
}
var _this = this,
$table = $(myTable.elem),
$tableBox = $table.next().children('.layui-table-box'),
$tableHead = $.merge($tableBox.children('.layui-table-header').children('table'), $tableBox.children('.layui-table-fixed').children('.layui-table-header').children('table')),
$fixedBody = $tableBox.children('.layui-table-fixed').children('.layui-table-body').children('table'),
$noFixedBody = $tableBox.children('.layui-table-body').children('table'),
$tableBody = $.merge($tableBox.children('.layui-table-body').children('table'), $fixedBody),
$totalTable = $table.next().children('.layui-table-total').children('table'),
$fixedTotalTable = $table.next().children('.layui-table-total').children('table.layui-table-total-fixed'),
$noFixedTotalTable = $table.next().children('.layui-table-total').children('table:eq(0)'),
tableId = myTable.id,
isSimple = dragConfig === 'simple' || (dragConfig && dragConfig.type === 'simple'), // 是否为简易拖拽
toolbar = dragConfig && dragConfig.toolbar, // 是否开启工具栏
isDragging = false, isStart = false;
if (!$tableHead.attr('drag')) {
$tableHead.attr('drag', true);
if (toolbar) {
$tableBox.append('<div class="soul-drag-bar"><div data-type="left">左固定</div><div data-type="none">不固定</div><div data-type="right">右固定</div></div>')
var $dragBar = $tableBox.children('.soul-drag-bar');
$dragBar.children('div').on('mouseenter', function () {
$(this).addClass('active')
}).on('mouseleave', function () {
$(this).removeClass('active')
})
}
$tableHead.find('th').each(function () {
var $this = $(this),
field = $this.data('field'),
key = $this.data('key');
if (!key) {
return;
}
var keyArray = key.split('-'),
curColumn = myTable.cols[keyArray[1]][keyArray[2]],
curKey = keyArray[1] + '-' + keyArray[2],
isInFixed = $this.parents('.layui-table-fixed').length > 0;
// 绑定鼠标按下事件
$(this).find('span:first,.laytable-cell-checkbox')
.css('cursor', 'move')
.on('mousedown', function (e) {
// 暂停或者非鼠标左键都不执行
if (_this.suspendConfig[tableId].drag || e.button !== 0) {
return;
}
e.preventDefault();
var $cloneHead = $this.clone().css('visibility', 'hidden'),
originLeft = $this.position().left,
originTop = $this.offset().top,
disX = e.clientX - originLeft, // 鼠标距离被移动元素左侧的距离
color = $this.parents('tr:eq(0)').css("background-color"),
width = $this.width(), moveDistince = 0,
$that = $(this),
isFixed = curColumn.fixed;
isStart = true;
//区分click、drag事件
// 阻止文本选中
_DOC.bind("selectstart", function () {
return false;
});
// 移动事件
_BODY.on('mousemove', function (e) {
if (isStart && $cloneHead) {
$tableBox.removeClass('no-left-border');
if (!isDragging) {
if (toolbar) {
$dragBar.attr('data-type', isFixed || 'none')
$dragBar.addClass('active')
}
$this.after($cloneHead);
$this.addClass('isDrag').css({
'position': 'absolute',
'z-index': 1,
'border-left': '1px solid #e6e6e6',
'background-color': color,
'width': width + 1
});
if (isSimple) {
//设置蒙板
} else {
(isInFixed ? $fixedBody : $tableBody).find('td[data-key="' + key + '"]').each(function () {
$(this).after($(this).clone().css('visibility', 'hidden').attr('data-clone', ''));
$(this).addClass('isDrag').css({
'position': 'absolute',
'z-index': 1,
'border-left': '1px solid #e6e6e6',
'background-color': $(this).css('background-color'),
'width': width + 1
});
})
if ($totalTable.length > 0) {
(isInFixed ? $fixedTotalTable : $totalTable).find('td[data-key="' + key + '"]').each(function () {
$(this).after($(this).clone().css('visibility', 'hidden').attr('data-clone', ''));
$(this).addClass('isDrag').css({
'position': 'absolute',
'z-index': 1,
'background-color': $(this).parents('tr:eq(0)').css('background-color'),
'width': width + 1
});
})
}
}
}
isDragging = true;
var x, y, i, j, tempCols,
left = e.clientX - disX, // 计算当前被移动列左侧位置应该哪里
$leftTh = $cloneHead.prev().prev(),
hasLeftTh = $leftTh.length > 0,
leftKey = hasLeftTh ? $leftTh.data('key').split('-') : [],
$rightTh = $cloneHead.next().hasClass('layui-table-patch') ? [] : $cloneHead.next(),
hasRightTh = $rightTh.length > 0,
rightKey = hasRightTh ? $rightTh.data('key').split('-') : [],
leftMove = hasLeftTh && ($cloneHead.position().left - left > $leftTh.width() / 2.0),
rightMove = hasRightTh && (left - $cloneHead.position().left > $rightTh.width() / 2.0);
moveDistince = Math.abs($cloneHead.position().left - left); //记录移动距离
// 移动到左右两端、checbox/radio 固定列等停止移动
if ($cloneHead.position().left - left > 0
? !hasLeftTh || !!isFixed !== !!myTable.cols[leftKey[1]][leftKey[2]].fixed
: !hasRightTh || !!isFixed !== !!myTable.cols[rightKey[1]][rightKey[2]].fixed) {
$this.css('left', $cloneHead.position().left);
$tableBody.find('td[data-key="' + key + '"][data-clone]').each(function (e) {
$(this).prev().css('left', $cloneHead.position().left);
})
if ($totalTable.length > 0) {
$totalTable.find('td[data-key="' + key + '"][data-clone]').each(function (e) {
$(this).prev().css('left', $cloneHead.position().left);
})
}
$tableBox.addClass('no-left-border');
return;
}
$this.css('left', left);
if (leftMove) {
$cloneHead.after($leftTh);
// 更新隐藏列顺序
$('#soul-columns' + tableId + '>li[data-value="' + field + '"]').after($('#soul-columns' + tableId + '>li[data-value="' + field + '"]').prev())
// 更新配置信息
for (i = 0; i < myTable.cols.length; i++) {
for (j = 0; j < myTable.cols[i].length; j++) {
if (myTable.cols[i][j].key === curKey) {
x = i;
y = j;
break;
}
}
if (typeof x !== 'undefined' && typeof y !== 'undefined') {
break;
}
}
tempCols = myTable.cols[x][y - 1];
myTable.cols[x][y - 1] = myTable.cols[x][y];
myTable.cols[x][y] = tempCols;
_this.fixTableRemember(myTable);
} else if (rightMove) {
$cloneHead.prev().before($rightTh);
// 更新隐藏列顺序
$('#soul-columns' + tableId + '>li[data-value="' + field + '"]').before($('#soul-columns' + tableId + '>li[data-value="' + field + '"]').next())
// 更新配置信息
for (i = 0; i < myTable.cols.length; i++) {
for (j = 0; j < myTable.cols[i].length; j++) {
if (myTable.cols[i][j].key === curKey) {
x = i;
y = j;
break;
}
}
if (typeof x !== 'undefined' && typeof y !== 'undefined') {
break;
}
}
tempCols = myTable.cols[x][y + 1];
myTable.cols[x][y + 1] = myTable.cols[x][y];
myTable.cols[x][y] = tempCols;
_this.fixTableRemember(myTable);
}
$tableBody.find('td[data-key="' + key + '"][data-clone]').each(function () {
$(this).prev().css('left', left);
if (leftMove) {
if ($(this).prev().prev().length !== 0) {
$(this).after($(this).prev().prev());
}
} else if (rightMove) {
if ($(this).next().length !== 0) {
$(this).prev().before($(this).next());
}
}
})
if ($totalTable.length > 0) {
$totalTable.find('td[data-key="' + key + '"][data-clone]').each(function () {
$(this).prev().css('left', left);
if (leftMove) {
if ($(this).prev().prev().length !== 0) {
$(this).after($(this).prev().prev());
}
} else if (rightMove) {
if ($(this).next().length !== 0) {
$(this).prev().before($(this).next());
}
}
})
}
/* 拖动隐藏列 */
if (e.clientY - originTop < -15) {
if ($('#column-remove').length === 0) {
_BODY.append('<i id="column-remove" class="layui-red layui-icon layui-icon-delete"></i>')
}
$('#column-remove').css({
top: e.clientY - $('#column-remove').height() / 2,
left: e.clientX - $('#column-remove').width() / 2,
'font-size': (originTop - e.clientY) + 'px'
})
$('#column-remove').show();
} else {
$('#column-remove').hide();
}
}
}).on('mouseup', function () {
_DOC.unbind("selectstart");
_BODY.off('mousemove').off('mouseup')
if (isStart && $cloneHead) {
isStart = false;
if (isDragging) {
if (curColumn.type !== 'checkbox') {
$that.on('click', function (e) {
e.stopPropagation();
});
}
isDragging = false;
$tableBox.removeClass('no-left-border')
$this.removeClass('isDrag').css({
'position': 'relative',
'z-index': 'inherit',
'left': 'inherit',
'border-left': 'inherit',
'width': 'inherit',
'background-color': 'inherit'
});
$this.next().remove();
var prefKey = $this.prev().data('key');
if (isFixed) {
var $noFixedTh = $tableBox.children('.layui-table-header').children('table').find('th[data-key="' + key + '"]');
if (prefKey) {
$noFixedTh.parent().children('th[data-key="' + prefKey + '"]').after($noFixedTh)
} else {
if (isFixed === 'right') {
if ($this.siblings().length > 0) {
$tableBox.children('.layui-table-header').children('table').find('th[data-key="' + $this.next().data('key') + '"]').prev().after($noFixedTh);
}
} else {
$noFixedTh.parent().prepend('<th class="layui-hide"></th>');
$noFixedTh.parent().children('th:first').after($noFixedTh);
$noFixedTh.parent().children('th:first').remove();
}
}
}
if (isSimple) {
$tableBody.find('td[data-key="' + key + '"]').each(function () {
if (prefKey) {
$(this).parent().children('td[data-key="' + prefKey + '"]').after($(this))
} else {
if (isFixed === 'right') {
if ($this.siblings().length > 0) {
var $preTd = $(this).parent().children('td[data-key="' + $this.next().data('key') + '"]').prev();
if ($preTd.length > 0) {
$preTd.after($(this));
} else {
$(this).parent().prepend('<td class="layui-hide"></td>');
$(this).parent().children('td:first').after($(this));
$(this).parent().children('td:first').remove();
}
}
} else {
$(this).parent().prepend('<td class="layui-hide"></td>');
$(this).parent().children('td:first').after($(this));
$(this).parent().children('td:first').remove();
}
}
});
if ($totalTable.length > 0) {
$totalTable.find('td[data-key="' + key + '"]').each(function () {
if (prefKey) {
$(this).parent().children('td[data-key="' + prefKey + '"]').after($(this))
} else {
if (isFixed === 'right') {
var $preTd = $(this).parent().children('td[data-key="' + $this.next().data('key') + '"]').prev();
if ($preTd.length > 0) {
$preTd.after($(this));
} else {
$(this).parent().prepend('<td class="layui-hide"></td>');
$(this).parent().children('td:first').after($(this));
$(this).parent().children('td:first').remove();
}
} else {
$(this).parent().prepend('<td class="layui-hide"></td>');
$(this).parent().children('td:first').after($(this));
$(this).parent().children('td:first').remove();
}
}
});
}
} else if (isInFixed) {
$noFixedBody.find('td[data-key="' + key + '"]').each(function () {
if (prefKey) {
$(this).parent().children('td[data-key="' + prefKey + '"]').after($(this))
} else {
if (isFixed === 'right') {
if ($this.siblings().length > 0) {
var $preTd = $(this).parent().children('td[data-key="' + $this.next().data('key') + '"]').prev();
if ($preTd.length > 0) {
$preTd.after($(this));
} else {
$(this).parent().prepend('<td class="layui-hide"></td>');
$(this).parent().children('td:first').after($(this));
$(this).parent().children('td:first').remove();
}
}
} else {
$(this).parent().prepend('<td class="layui-hide"></td>');
$(this).parent().children('td:first').after($(this));
$(this).parent().children('td:first').remove();
}
}
});
$fixedBody.find('td[data-key="' + key + '"][data-clone]').each(function () {
$(this).prev().removeClass('isDrag').css({
'position': 'relative',
'z-index': 'inherit',
'left': 'inherit',
'border-left': 'inherit',
'width': 'inherit',
'background-color': 'inherit'
});
$(this).remove();
});
if ($totalTable.length > 0) {
$noFixedTotalTable.find('td[data-key="' + key + '"]').each(function () {
if (prefKey) {
$(this).parent().children('td[data-key="' + prefKey + '"]').after($(this))
} else {
if (isFixed === 'right') {
var $preTd = $(this).parent().children('td[data-key="' + $this.next().data('key') + '"]').prev();
if ($preTd.length > 0) {
$preTd.after($(this));
} else {
$(this).parent().prepend('<td class="layui-hide"></td>');
$(this).parent().children('td:first').after($(this));
$(this).parent().children('td:first').remove();
}
} else {
$(this).parent().prepend('<td class="layui-hide"></td>');
$(this).parent().children('td:first').after($(this));
$(this).parent().children('td:first').remove();
}
}
});
$fixedTotalTable.find('td[data-key="' + key + '"][data-clone]').each(function () {
$(this).prev().removeClass('isDrag').css({
'position': 'relative',
'z-index': 'inherit',
'left': 'inherit',
'width': 'inherit',
'background-color': 'inherit'
});
$(this).remove();
});
}
} else {
$tableBody.find('td[data-key="' + key + '"][data-clone]').each(function () {
$(this).prev().removeClass('isDrag').css({
'position': 'relative',
'z-index': 'inherit',
'left': 'inherit',
'width': 'inherit',
'background-color': 'inherit'
});
$(this).remove();
});
if ($totalTable.length > 0) {
$totalTable.find('td[data-key="' + key + '"][data-clone]').each(function () {
$(this).prev().removeClass('isDrag').css({
'position': 'relative',
'z-index': 'inherit',
'left': 'inherit',
'width': 'inherit',
'background-color': 'inherit'
});
$(this).remove();
});
}
}
$cloneHead = null;
// 处理 toolbar 事件
if (toolbar) {
if ($dragBar.children('.active').length > 0 && $dragBar.children('.active').attr('data-type') !== $dragBar.attr('data-type')) {
var targetFix = $dragBar.children('.active').attr('data-type'),
i, j, curPos, targetPos;
for (i = 0; i < myTable.cols.length; i++) {
for (j = 0; j < myTable.cols[i].length; j++) {
if (targetFix === 'right' || (targetFix === 'none' && $dragBar.attr('data-type') === 'right')) {
if (typeof targetPos === 'undefined') {
if (myTable.cols[i][j].fixed === 'right') {
targetPos = {x: i, y: j};
} else if (j === myTable.cols[i].length - 1) {
targetPos = {x: i, y: j + 1};
}
}
} else {
if (typeof targetPos === 'undefined' && (!myTable.cols[i][j].fixed || myTable.cols[i][j].fixed === 'right')) {
targetPos = {x: i, y: j};
}
}
if (myTable.cols[i][j].key === curKey) {
curPos = {x: i, y: j};
}
}
}
curColumn['fixed'] = targetFix === 'none' ? false : targetFix;
if (curPos.y !== targetPos.y) {
myTable.cols[curPos.x].splice(curPos.y, 1);
if (curPos.y < targetPos.y) {
targetPos.y -= 1
}
myTable.cols[targetPos.x].splice(targetPos.y, 0, curColumn)
_this.fixTableRemember(myTable);
}
table.reload(tableId)
}
$dragBar.removeClass('active')
}
} else {
$that.unbind('click');
}
if ($('#column-remove').is(':visible')) {
$tableHead.find('thead>tr>th[data-key=' + key + ']').addClass(HIDE);
$tableBody.find('tbody>tr>td[data-key="' + key + '"]').addClass(HIDE);
$totalTable.find('tbody>tr>td[data-key="' + key + '"]').addClass(HIDE);
// 同步配置
curColumn['hide'] = true
_this.fixTableRemember(myTable);
// 更新下拉隐藏
$('#soul-columns' + tableId).find('li[data-value="' + field + '"]>input').prop('checked', false);
}
$('#column-remove').hide();
}
})
});
})
}
},
rowDrag: function (myTable, rowDragConfig) {
var _this = this,
$table = $(myTable.elem),
$tableBox = $table.next().children('.layui-table-box'),
$fixedBody = $tableBox.children('.layui-table-fixed').children('.layui-table-body').children('table'),
$noFixedBody = $tableBox.children('.layui-table-body').children('table'),
$tableBody = $.merge($tableBox.children('.layui-table-body').children('table'), $fixedBody),
tableId = myTable.id,
isDragging = false,
trigger = rowDragConfig.trigger || 'row',
syncNumber = rowDragConfig.numbers !== false,
numberColumnKey = null, numberStart = 0,
$trs = trigger === 'row' ? $tableBody.children('tbody').children('tr') : $tableBody.find(trigger),
i, j;
if (trigger !== 'row') {
$tableBody.find(trigger).css('cursor', 'move')
}
for (i = 0; i < myTable.cols.length; i++) {
for (j = 0; j < myTable.cols[i].length; j++) {
if (myTable.cols[i][j].type === 'numbers') {
numberColumnKey = myTable.index + '-' + i + '-' + j;
numberStart = parseInt($noFixedBody.find('td[data-key="' + numberColumnKey + '"]:first').text());
break;
}
}
}
$trs.on('mousedown', function (e) {
// 被暂停 或者 不是鼠标左键 则取消拖拽效果
if (_this.suspendConfig[tableId].rowDrag || e.button !== 0) {
return;
}
var $this = trigger === 'row' ? $(this) : $(this).parents('tr:eq(0)'),
index = parseInt($this.data('index')), // 被拖拽行索引
$bodyTr = $noFixedBody.children('tbody').children('tr[data-index=' + index + ']'), // 被拖拽行(非固定列)
$cloneTr = $bodyTr.clone().css('visibility', 'hidden'), // 占位行
$FixBodyTr = $fixedBody.children('tbody').children('tr[data-index=' + index + ']'), // 被拖拽行(固定列)
bodyScrollTop = $tableBox.children('.layui-table-body').scrollTop(), // 记录当前滚动条位置
originTop = $this.position().top, // 被拖拽行当前位置
disY = e.clientY - originTop; // 鼠标距离被拖拽行上侧的距离
_BODY.on('mousemove', function (e) {
// 刚被拖动
if (!isDragging) {
isDragging = true;
// 设置鼠标样式
// $table.next().find('style').append('.layui-table-view .layui-table td{cursor: move;}.layui-table tr{transition: none}')
var style = $table.next().find('style')[0],
sheet = style.sheet || style.styleSheet || {};
_this.addCSSRule(sheet, '.layui-table-view .layui-table td', 'cursor: move')
_this.addCSSRule(sheet, '.layui-table tr', 'transition: none')
$tableBox.addClass('noselect'); // 禁止选中文本
$bodyTr.after($cloneTr);
$bodyTr.css({
'position': 'absolute',
'z-index': 1
})
$FixBodyTr.each(function () {
$(this).after($(this).clone().css('visibility', 'hidden'))
$(this).css({
'position': 'absolute',
'z-index': 102
})
})
}
var top = e.clientY - disY + ($tableBox.children('.layui-table-body').scrollTop() - bodyScrollTop), // 计算当前被移动行top位置应该哪里
trTop = $cloneTr.position().top, //当前行所在位置
$UpTr = $bodyTr.prev(),
hasUpTr = $UpTr.length > 0,
$downTr = $cloneTr.next(),
hasDownTr = $downTr.length > 0,
upMove = hasUpTr && (trTop - top > $UpTr.height() / 2.0),
downMove = hasDownTr && (top - trTop > $downTr.height() / 2.0);
if (trTop - top > 0 ? !hasUpTr : !hasDownTr) {
$bodyTr.css('top', trTop);
$FixBodyTr.each(function () {
$(this).css('top', trTop);
})
return;
}
$bodyTr.css('top', top);
$FixBodyTr.each(function () {
$(this).css('top', top);
})
if (upMove) {
updateDataIndex($bodyTr, -1)
$cloneTr.after(updateDataIndex($UpTr, 1));
$FixBodyTr.each(function () {
updateDataIndex($(this), -1)
$(this).next().after(updateDataIndex($(this).prev(), 1));
})
} else if (downMove) {
updateDataIndex($bodyTr, 1).before(updateDataIndex($downTr, -1))
$FixBodyTr.each(function () {
updateDataIndex($(this), 1);
$(this).before(updateDataIndex($(this).next().next(), -1));
})
}
// 同步 data-index
function updateDataIndex($el, diff) {
var tempIndex = parseInt($el.data('index')) + diff;
$el.data('index', tempIndex);
$el.attr('data-index', tempIndex);
return $el
}
}).on('mouseup', function (e) {
_BODY.off('mousemove').off('mouseup');
if (isDragging) {
isDragging = false;
$tableBox.removeClass('noselect'); // 取消禁止选中文本
$bodyTr.css({'position': 'inherit', 'z-index': 'inherit'});
$bodyTr.next().remove();
$FixBodyTr.each(function () {
$(this).css({'position': 'inherit', 'z-index': 'inherit'});
$(this).next().remove()
})
// 恢复样式
var style = $table.next().find('style')[0],
sheet = style.sheet || style.styleSheet || {},
rules = sheet.cssRules || sheet.rules;
layui.each(rules, function (i, item) {
if (item.selectorText === ('.layui-table-view .layui-table td')) {
item.style.cursor = 'default';
}
});
var newIndex = $this.index(),
cache = table.cache[tableId];
if (newIndex !== index) { // 有位置变动
// 如果 before 返回 false,则还原拖拽
if (typeof rowDragConfig.before === 'function'
&& rowDragConfig.before.call(myTable, {
row: cache[index],
newIndex: newIndex,
oldIndex: index,
cache: cache
}) === false) {
// 同步 data-index
function updateDataIndex($el, setIndex) {
$el.data('index', setIndex);
$el.attr('data-index', setIndex);
return $el
}
// 还原位置和索引
if (newIndex < index) {
for (i = newIndex; i < index; i++) {
updateDataIndex($noFixedBody.find('tr[data-index="'+(i+1)+'"]'), i)
updateDataIndex($fixedBody.find('tr[data-index="'+(i+1)+'"]'), i)
}
updateDataIndex($bodyTr, index)
$noFixedBody.find('tr[data-index="'+(index - 1)+'"]').after($bodyTr)
$FixBodyTr.each(function () {
updateDataIndex($(this), index)
$(this).parent().children('tr[data-index="'+(index - 1)+'"]').after($(this))
})
} else {
for (i = newIndex; i > index; i--) {
updateDataIndex($noFixedBody.find('tr[data-index="'+(i-1)+'"]'), i)
updateDataIndex($fixedBody.find('tr[data-index="'+(i-1)+'"]'), i)
}
updateDataIndex($bodyTr, index)
$noFixedBody.find('tr[data-index="'+(index + 1)+'"]').before($bodyTr)
$FixBodyTr.each(function () {
updateDataIndex($(this), index)
$(this).parent().children('tr[data-index="'+(index + 1)+'"]').before($(this))
})
}
return;
}
var row = cache.splice(index, 1)[0];
cache.splice(newIndex, 0, row);
if (numberColumnKey && syncNumber) {
// 进行序号重排
var sortedIndexs = [newIndex, index].sort()
for (i = sortedIndexs[0]; i <= sortedIndexs[1]; i++) {
var curIndex = numberStart + i;
$fixedBody.find('td[data-key="' + numberColumnKey + '"]:eq(' + i + ')').children().html(curIndex)
$noFixedBody.find('td[data-key="' + numberColumnKey + '"]:eq(' + i + ')').children().html(curIndex)
cache[i][table.config.indexName] = curIndex - 1
}
}
if (typeof rowDragConfig.done === 'function') {
rowDragConfig.done.call(myTable, {
row: row,
newIndex: newIndex,
oldIndex: index,
cache: cache
})
}
}
}
})
})
},
fixTableRemember: function (myTable, dict) {
if (typeof myTable.filter === 'undefined' ? (defaultConfig.filter && defaultConfig.filter.cache) : myTable.filter.cache) {
if (dict && dict.rule) {
var curKey = dict.rule.selectorText.split('-')[3] + '-' + dict.rule.selectorText.split('-')[4];
for (var i = 0; i < myTable.cols.length; i++) {
for (var j = 0; j < myTable.cols[i].length; j++) {
if (myTable.cols[i][j].key === curKey) {
myTable.cols[i][j].width = dict.rule.style.width.replace('px', '');
break;
}
}
}
}
var storeKey = location.pathname + location.hash + myTable.id;
localStorage.setItem(storeKey, this.deepStringify(myTable.cols))
}
},
clearCache: function (myTable) {
if (!myTable) {
return;
}
var tableId;
if (typeof myTable === 'object') {
if (typeof myTable.config !== 'undefined') {
tableId = myTable.config.id
} else {
tableId = myTable.id
}
} else {
tableId = myTable
}
localStorage.removeItem(location.pathname + location.hash + tableId)
if (originCols[tableId]) {
this.updateCols(tables[tableId], this.deepClone(originCols[tableId]))
}
},
overflow: function (myTable, overflowConfig) {
var options = {};
if (typeof overflowConfig === 'string') {
options = {
type: overflowConfig
}
} else if (typeof overflowConfig === 'object') {
options = overflowConfig
} else {
return;
}
var $table = $(myTable.elem),
layHeader = $table.next().find('.layui-table-header'),
layBody = $table.next().find('.layui-table-body'),
layTotal = $table.next().find('.layui-table-total'),
tooltipIndex,
hoverTime = options.hoverTime || 0,
tooltipTimeOut,
color = options.color || 'white',
bgColor = options.bgColor || 'black',
minWidth = options.minWidth || 300,
maxWidth = options.maxWidth || 300;
if (options.type === 'tips') {
layBody.off('mouseenter', 'td').off('mouseleave', 'td').on('mouseenter', 'td', function () {
var _this = this;
tooltipTimeOut = setTimeout(function () {
toopTip.call(_this)
}, hoverTime)
}).on('mouseleave', 'td', function () {
toopTip.call(this, 'hide')
})
if (options.header) {
layHeader.off('mouseenter', 'th').off('mouseleave', 'th').on('mouseenter', 'th', function () {
var _this = this;
tooltipTimeOut = setTimeout(function () {
toopTip.call(_this)
}, hoverTime)
}).on('mouseleave', 'th', function () {
toopTip.call(this, 'hide')
})
}
if (options.total) {
layTotal.off('mouseenter', 'td').off('mouseleave', 'td').on('mouseenter', 'td', function () {
var _this = this;
tooltipTimeOut = setTimeout(function () {
toopTip.call(_this)
}, hoverTime)
}).on('mouseleave', 'td', function () {
toopTip.call(this, 'hide')
})
}
function toopTip(hide) {
clearTimeout(tooltipTimeOut);
var othis = $(this)
, elemCell = othis.children('.layui-table-cell')
, width = elemCell.outerWidth()
, layerWidth = width < minWidth ? minWidth : width > maxWidth ? maxWidth : width;
if (othis.data('off')) return;
if (hide) {
layer.close(tooltipIndex)
} else if (elemCell.prop('scrollWidth') > width) {
tooltipIndex = layer.tips('<span style="color: ' + color + '">' + $(this).text() + '</span>', this, {
tips: [1, bgColor],
maxWidth: layerWidth,
time: 0
});
}
}
} else if (options.type === 'title') {
layBody.off('mouseenter', 'td').on('mouseenter', 'td', function () {
var othis = $(this)
, elemCell = othis.children('.layui-table-cell');
if (othis.data('off')) return;
if (elemCell.prop('scrollWidth') > elemCell.outerWidth()) {
elemCell.attr('title', $(this).text())
}
})
if (options.header) {
layHeader.off('mouseenter', 'th').on('mouseenter', 'th', function () {
var othis = $(this)
, elemCell = othis.children('.layui-table-cell');
if (othis.data('off')) return;
if (elemCell.prop('scrollWidth') > elemCell.outerWidth()) {
elemCell.attr('title', $(this).text())
}
})
}
if (options.total) {
layTotal.off('mouseenter', 'td').on('mouseenter', 'td', function () {
var othis = $(this)
, elemCell = othis.children('.layui-table-cell');
if (othis.data('off')) return;
if (elemCell.prop('scrollWidth') > elemCell.outerWidth()) {
elemCell.attr('title', $(this).text())
}
})
}
}
},
// 右键菜单配置
contextmenu: function (myTable, contextmenuConfig) {
var $table = $(myTable.elem),
$tableBox = $table.next().children('.layui-table-box'),
$tableHead = $.merge($tableBox.children('.layui-table-header').children('table'), $tableBox.children('.layui-table-fixed').children('.layui-table-header').children('table')),
$fixedBody = $tableBox.children('.layui-table-fixed').children('.layui-table-body').children('table'),
$tableBody = $.merge($tableBox.children('.layui-table-body').children('table'), $fixedBody),
$totalTable = $table.next().children('.layui-table-total').children('table'),
tableId = myTable.id,
header = contextmenuConfig ? contextmenuConfig.header : '',
body = contextmenuConfig ? contextmenuConfig.body : '',
total = contextmenuConfig ? contextmenuConfig.total : '',
options = {
header: {box: $tableHead, tag: 'th', opts: header, cols: {}},
body: {box: $tableBody, tag: 'td', opts: body, cols: {}, isBody: true},
total: {box: $totalTable, tag: 'td', opts: total, cols: {}}
},
hasColsContext = false;
for (var i = 0; i < myTable.cols.length; i++) {
for (var j = 0; j < myTable.cols[i].length; j++) {
if (myTable.cols[i][j].contextmenu) {
hasColsContext = true
options.header.cols[myTable.cols[i][j].key] = myTable.cols[i][j].contextmenu.header
options.body.cols[myTable.cols[i][j].key] = myTable.cols[i][j].contextmenu.body
options.total.cols[myTable.cols[i][j].key] = myTable.cols[i][j].contextmenu.total
}
}
}
if (!contextmenuConfig && !hasColsContext) {
return;
}
for (var name in options) {
(function (name) {
options[name].box.find(options[name].tag).on('contextmenu', function (e) {
$('#soul-table-contextmenu-wrapper').remove();
_BODY.append('<div id="soul-table-contextmenu-wrapper"></div>');
$('#soul-table-contextmenu-wrapper').on('click', function (e) {
e.stopPropagation()
})
var curColsOpts = options[name].cols[$(this).data('key').substr($(this).data('key').indexOf('-') + 1)];
if (curColsOpts === false) {
return false
} else if (curColsOpts && curColsOpts.length > 0) {
genePanel($('#soul-table-contextmenu-wrapper'), e.pageX, e.pageY, curColsOpts, $(this), options[name].box, options[name].tag, options[name].isBody);
return false
} else if (options[name].opts === false) {
return false
} else if (options[name].opts && options[name].opts.length > 0) {
genePanel($('#soul-table-contextmenu-wrapper'), e.pageX, e.pageY, options[name].opts, $(this), options[name].box, options[name].tag, options[name].isBody);
return false
}
})
})(name)
}
_BODY.on('click', function () {
$('#soul-table-contextmenu-wrapper').remove();
})
function genePanel($parent, left, top, options, $this, box, tag, isBody) {
var html = [], i;
html.push('<ul class="soul-table-contextmenu">');
for (i = 0; i < options.length; i++) {
html.push('<li data-index="' + i + '" class="' + (options[i].children && options[i].children.length > 0 ? 'contextmenu-children' : '') + '">')
if (options[i].icon) {
html.push('<i class="prefixIcon ' + options[i].icon + '" />')
} else {
html.push('<i class="prefixIcon" />')
}
html.push(options[i].name)
if (options[i].children && options[i].children.length > 0) {
html.push('<i class="endIcon layui-icon layui-icon-right" />')
}
html.push('</li>')
}
html.push('</ul>');
$parent.append(html.join(''));
var $curPanel = $parent.children().last();
if (top + $curPanel.outerHeight() > _BODY.prop('scrollHeight')) {
top = top - $curPanel.outerHeight()
if (top < 0) {
top = 0
}
}
if ($parent.parent().data('direction') === 'left' && ($parent.offset().left - $curPanel.outerWidth()) > 0) {
left = -$curPanel.outerWidth();
$curPanel.data('direction', 'left')
} else if (left + $curPanel.outerWidth() + $parent.offset().left > _BODY.prop('scrollWidth')) {
left = left - $curPanel.outerWidth() - $parent.outerWidth()
if (left + $parent.offset().left < 0) {
left = -$parent.offset().left
}
$curPanel.data('direction', 'left')
}
$curPanel.css({
top: top + 'px',
left: left + 'px'
})
for (i = 0; i < options.length; i++) {
if (typeof options[i].click === "function") {
(function (i) {
$parent.children('.soul-table-contextmenu:last').children('li[data-index="' + i + '"]').on('click', function () {
var index = $this.parents('tr:eq(0)').data('index'),
tr = box.find('tr[data-index="' + index + '"]'),
row = layui.table.cache[tableId][index];
options[i].click.call(myTable, {
cell: $this,
elem: tag === 'th' ? $this : isBody ? box.children('tbody').children('tr[data-index="' + index + '"]').children('[data-key="' + $this.data('key') + '"]') : box.find('[data-key="' + $this.data('key') + '"]'),
trElem: box.children('tbody').children('tr[data-index="' + index + '"]'),
text: $this.text(),
field: $this.data('field'),
del: !isBody ? '' : function () {
table.cache[tableId][index] = [];
tr.remove();
table.resize(tableId);
},
update: !isBody ? '' : function (fields) {
fields = fields || {};
layui.each(fields, function (key, value) {
if (key in row) {
var templet, td = tr.children('td[data-field="' + key + '"]');
row[key] = value;
table.eachCols(tableId, function (i, item2) {
if (item2.field == key && item2.templet) {
templet = item2.templet;
}
});
td.children('.layui-table-cell').html(function () {
return templet ? function () {
return typeof templet === 'function'
? templet(row)
: layui.laytpl($(templet).html() || value).render(row)
}() : value;
}());
td.data('content', value);
}
});
},
row: isBody ? row : {},
})
$('#soul-table-contextmenu-wrapper').remove();
})
})(i)
}
}
$parent.children('.soul-table-contextmenu:last').children('li').on('mouseenter', function (e) {
e.stopPropagation()
$(this).siblings('.contextmenu-children').children('ul').remove();
if ($(this).hasClass('contextmenu-children')) {
genePanel($(this), $(this).outerWidth(), $(this).position().top, options[$(this).data('index')].children, $this, box, tag, isBody)
}
})
}
},
fixTotal: function (myTable) {
var $table = $(myTable.elem),
$total = $table.next().children('.layui-table-total'),
style = $table.next().find('style')[0],
sheet = style.sheet || style.styleSheet || {};
if ($total.length > 0) {
var $tableBox = $table.next().children('.layui-table-box'),
$fixedLeft = $tableBox.children('.layui-table-fixed-l').children('.layui-table-body').children('table').children('tbody').children('tr:eq(0)').children('td'),
$fixedRight = $tableBox.children('.layui-table-fixed-r').children('.layui-table-body').children('table').children('tbody').children('tr:eq(0)').children('td'),
html = [];
$total.children('.layui-table-total-fixed').remove()
if ($fixedLeft.length > 0) {
this.addCSSRule(sheet, '.layui-table-total-fixed-l .layui-table-patch', 'display: none')
$table.next().css('position', 'relative');
html.push('<table style="position: absolute;background-color: #fff;left: 0;top: ' + ($total.position().top + 1) + 'px" cellspacing="0" cellpadding="0" border="0" class="layui-table layui-table-total-fixed layui-table-total-fixed-l"><tbody><tr>');
$fixedLeft.each(function () {
if ($(this).data('key')) {
html.push($total.children('table:eq(0)').find('[data-key="' + $(this).data('key') + '"]').prop("outerHTML"))
}
})
html.push('</tr></tbody></table>');
$total.append(html.join(''))
}
if ($fixedRight.length > 0) {
this.addCSSRule(sheet, '.layui-table-total-fixed-r td:first-child', 'border-left:1px solid #e6e6e6')
this.addCSSRule(sheet, '.layui-table-total-fixed-r td:last-child', 'border-left: none')
$table.next().css('position', 'relative');
html = [];
html.push('<table style="position: absolute;background-color: #fff;right: 0;top: ' + ($total.position().top + 1) + 'px" cellspacing="0" cellpadding="0" border="0" class="layui-table layui-table-total-fixed layui-table-total-fixed-r"><tbody><tr>');
$fixedRight.each(function () {
html.push($total.children('table:eq(0)').find('[data-key="' + $(this).data('key') + '"]').prop("outerHTML"))
})
html.push('</tr></tbody></table>')
$total.append(html.join(''))
}
}
},
fixResizeRightFixed: function (myTable) {
var _this = this,
$table = $(myTable.elem),
$tableBox = $table.next().children('.layui-table-box'),
$fixedHead = $tableBox.children('.layui-table-fixed-r').children('.layui-table-header').children('table'),
dict = {}, resizing, ELEM_SORT = 'layui-table-sort',
ELEM_NO_SORT = 'layui-table-sort-invalid';
if ($fixedHead.length > 0) {
$fixedHead.find('th').off('mousemove').on('mousemove', function (e) {
var othis = $(this)
, oLeft = othis.offset().left
, pLeft = e.clientX - oLeft;
if (othis.data('unresize') || dict.resizeStart) {
return;
}
if (othis.width() - pLeft <= 10) {
_BODY.css('cursor', 'initial')
}
dict.allowResize = pLeft <= 10; //是否处于拖拽允许区域
_BODY.css('cursor', (dict.allowResize ? 'col-resize' : ''));
}).off('mousedown').on('mousedown', function (e) {
var othis = $(this);
if (dict.allowResize) {
othis.find('.' + ELEM_SORT).removeClass(ELEM_SORT).addClass(ELEM_NO_SORT)
var key = othis.data('key');
e.preventDefault();
dict.resizeStart = true; //开始拖拽
dict.offset = [e.clientX, e.clientY]; //记录初始坐标
_this.getCssRule(myTable, key, function (item) {
var width = item.style.width || othis.outerWidth();
dict.rule = item;
dict.ruleWidth = parseFloat(width);
dict.othis = othis;
dict.minWidth = othis.data('minwidth') || myTable.cellMinWidth;
});
}
});
//拖拽中
_DOC.on('mousemove', function (e) {
if (dict.resizeStart) {
layui.soulTable.fixTableRemember(myTable, dict)
e.preventDefault();
if (dict.rule) {
var setWidth = dict.ruleWidth - e.clientX + dict.offset[0];
if (setWidth < dict.minWidth) setWidth = dict.minWidth;
dict.rule.style.width = setWidth + 'px';
}
resizing = 1
}
}).on('mouseup', function (e) {
if (dict.resizeStart) {
setTimeout(function () {
dict.othis.find('.' + ELEM_NO_SORT).removeClass(ELEM_NO_SORT).addClass(ELEM_SORT)
_BODY.css('cursor', '');
dict = {};
_this.scrollPatch(myTable);
}, 30)
}
if (resizing === 2) {
resizing = null;
}
});
}
},
fixFixedScroll: function (myTable) {
var $table = $(myTable.elem),
layFixed = $table.next().children('.layui-table-box').children('.layui-table-fixed'),
layMain = $table.next().children('.layui-table-box').children('.layui-table-main');
layFixed.on('mouseenter', function () {
$(this).children('.layui-table-body').addClass('soul-fixed-scroll').on('scroll', function () {
var scrollTop = $(this).scrollTop()
// layFixed.children('.layui-table-body[class!="soul-fixed-scroll"]').scrollTop(scrollTop);
layMain.scrollTop(scrollTop);
})
}).on('mouseleave', function () {
$(this).children('.layui-table-body').removeClass('soul-fixed-scroll').off('scroll');
})
},
scrollPatch: function (myTable) {
var $table = $(myTable.elem),
layHeader = $table.next().children('.layui-table-box').children('.layui-table-header'),
layTotal = $table.next().children('.layui-table-total'),
layMain = $table.next().children('.layui-table-box').children('.layui-table-main'),
layFixed = $table.next().children('.layui-table-box').children('.layui-table-fixed'),
layFixRight = $table.next().children('.layui-table-box').children('.layui-table-fixed-r'),
layMainTable = layMain.children('table'),
scollWidth = layMain.width() - layMain.prop('clientWidth'),
scollHeight = layMain.height() - layMain.prop('clientHeight'),
outWidth = layMainTable.outerWidth() - layMain.width() //表格内容器的超出宽度
//添加补丁
, addPatch = function (elem) {
if (scollWidth && scollHeight) {
elem = elem.eq(0);
if (!elem.find('.layui-table-patch')[0]) {
var patchElem = $('<th class="layui-table-patch"><div class="layui-table-cell"></div></th>'); //补丁元素
patchElem.find('div').css({
width: scollWidth
});
elem.find('tr').append(patchElem);
}
} else {
elem.find('.layui-table-patch').remove();
}
}
addPatch(layHeader);
addPatch(layTotal);
//固定列区域高度
var mainHeight = layMain.height()
, fixHeight = mainHeight - scollHeight;
layFixed.find('.layui-table-body').css('height', layMainTable.height() >= fixHeight ? fixHeight : 'auto');
//表格宽度小于容器宽度时,隐藏固定列
layFixRight[outWidth > 0 ? 'removeClass' : 'addClass'](HIDE);
//操作栏
layFixRight.css('right', scollWidth - 1);
},
/**
* 一键粘贴
* @param {String} text [需要 copy 的属性,默认是 innerText,主要用途例如赋值 a 标签上的 href 链接]
*
* range + selection
*
* 1.创建一个 range
* 2.把内容放入 range
* 3.把 range 放入 selection
*
* 注意:参数 attr 不能是自定义属性
* 注意:对于 user-select: none 的元素无效
* 注意:当 id 为 false 且 attr 不会空,会直接复制 attr 的内容
*/
copy: function (text) {
var target;
if (text) {
target = document.createElement('div');
target.id = 'tempTarget';
target.style.opacity = '0';
target.innerText = text;
document.body.appendChild(target);
} else {
target = document.querySelector('#' + id);
}
try {
var range = document.createRange();
range.selectNode(target);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
document.execCommand('copy');
window.getSelection().removeAllRanges();
} catch (e) {
console.log('复制失败')
}
if (text) {
// remove temp target
target.parentElement.removeChild(target);
}
},
addCSSRule: function (sheet, selector, rules, index) {
if ('insertRule' in sheet) {
sheet.insertRule(selector + '{' + rules + '}', index)
} else if ('addRule' in sheet) {
sheet.addRule(selector, rules, index)
}
},
deepStringify: function (obj) {
var JSON_SERIALIZE_FIX = {
PREFIX: "[[JSON_FUN_PREFIX_",
SUFFIX: "_JSON_FUN_SUFFIX]]"
};
return JSON.stringify(obj, function (key, value) {
if (typeof value === 'function') {
return JSON_SERIALIZE_FIX.PREFIX + value.toString() + JSON_SERIALIZE_FIX.SUFFIX;
}
return value;
});
},
deepParse: function (str) {
var JSON_SERIALIZE_FIX = {
PREFIX: "[[JSON_FUN_PREFIX_",
SUFFIX: "_JSON_FUN_SUFFIX]]"
};
return JSON.parse(str, function (key, value) {
if (typeof value === 'string' &&
value.indexOf(JSON_SERIALIZE_FIX.SUFFIX) > 0 && value.indexOf(JSON_SERIALIZE_FIX.PREFIX) === 0) {
return eval("(" + value.replace(JSON_SERIALIZE_FIX.PREFIX, "").replace(JSON_SERIALIZE_FIX.SUFFIX, "") + ")");
}
return value;
}) || {};
},
// 深度克隆-不丢失方法
deepClone: function (obj) {
var newObj = Array.isArray(obj) ? [] : {}
if (obj && typeof obj === "object") {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
newObj[key] = (obj && typeof obj[key] === 'object') ? this.deepClone(obj[key]) : obj[key];
}
}
}
return newObj
},
clearOriginCols: function (tableId) {
if (tableId) {
delete originCols[tableId]
} else {
originCols = {}
}
},
suspendConfig: {},
/**
* 暂停某个特性
* @param tableId
* @param type 暂停的类型,支持 'drag' 'rowDrag'
* @param value true/false
*/
suspend: function (tableId, type, value) {
this.suspendConfig[tableId][type] = value
}
}
// 输出
exports('soulTable', mod);
});
/**
*
* @name: 子表格扩展
* @author: yelog
* @link: https://github.com/yelog/layui-soul-table
* @license: MIT
* @version: v1.6.4
*/
layui.define(['table', 'element', 'form', 'laytpl'], function (exports) {
var $ = layui.jquery,
table = layui.table,
laytpl = layui.laytpl,
tableChildren = {},
HIDE = 'layui-hide',
ELEM_HOVER = 'soul-table-hover';
// 封装方法
var mod = {
/**
* 渲染入口
* @param myTable
*/
render: function (myTable) {
var _this = this,
$table = $(myTable.elem),
$tableBox = $table.next().children('.layui-table-box'),
tableId = myTable.id,
$tableHead = $tableBox.children('.layui-table-header').children('table'),
$fixedBody = $tableBox.children('.layui-table-fixed').children('.layui-table-body').children('table'),
$noFixedBody = $tableBox.children('.layui-table-body').children('table'),
$tableBody = $.merge($tableBox.children('.layui-table-body').children('table'), $fixedBody),
columns = _this.getCompleteCols(myTable.cols),
childIndex = [],
soulSort = typeof myTable.soulSort === 'undefined' || myTable.soulSort,
i;
// 修复hover样式
_this.fixHoverStyle(myTable)
// 获取子表配置信息
for (i = 0; i < columns.length; i++) {
if (columns[i].children && columns[i].children.length > 0) {
childIndex.push(i);
}
}
if (typeof $table.attr('lay-filter') === 'undefined') {
$table.attr('lay-filter', tableId);
}
// 绑定一下主表事件
if ($table.parents('.childTr').length === 0) {
// 行单击事件
if (typeof myTable.rowEvent === 'function') {
table.on('row(' + $table.attr('lay-filter') + ')', function (obj) {
myTable.rowEvent(_this.commonMember.call(this, _this, myTable, obj));
})
}
// 行双击事件
if (typeof myTable.rowDoubleEvent === 'function') {
table.on('rowDouble(' + $table.attr('lay-filter') + ')', function (obj) {
myTable.rowDoubleEvent(_this.commonMember.call(this, _this, myTable, obj));
})
}
// 绑定 checkbox 事件
if (typeof myTable.checkboxEvent === 'function') {
table.on('checkbox(' + $table.attr('lay-filter') + ')', function (obj) {
myTable.checkboxEvent(_this.commonMember.call(this, _this, myTable, obj));
})
}
// 绑定 edit 事件
if (typeof myTable.editEvent === 'function') {
table.on('edit(' + $table.attr('lay-filter') + ')', function (obj) {
myTable.editEvent(_this.commonMember.call(this, _this, myTable, obj));
})
}
// 绑定 tool 事件
if (typeof myTable.toolEvent === 'function') {
table.on('tool(' + $table.attr('lay-filter') + ')', function (obj) {
myTable.toolEvent(_this.commonMember.call(this, _this, myTable, obj));
})
}
// 绑定 toolbar 事件
if (typeof myTable.toolbarEvent === 'function') {
table.on('toolbar(' + $table.attr('lay-filter') + ')', function (obj) {
myTable.toolbarEvent(_this.commonMember.call(this, _this, myTable, obj));
})
}
}
if (childIndex.length > 0) {
for (i = 0; i < childIndex.length; i++) {
(function f() {
var child = columns[childIndex[i]]
, curIndex = childIndex[i]
, icon = child.icon || ['layui-icon layui-icon-right', 'layui-icon layui-icon-down'];
if (soulSort && !(myTable.url && myTable.page)) {
// 前台排序
table.on('sort(' + $table.attr('lay-filter') + ')', function () {
_this.render(myTable)
});
}
if (child.isChild && typeof child.isChild === 'function') {
$tableBody.find('tr').find('td[data-key$="' + child.key + '"]>div').each(function () {
if (child.isChild(layui.table.cache[tableId][$(this).parents('tr:eq(0)').data('index')])) {
if (child.field) {
$(this).prepend('<i style="cursor: pointer" class="childTable ' + icon[0] + '"></i>');
} else {
$(this).html('<i style="cursor: pointer" class="childTable ' + icon[0] + '"></i>');
}
}
})
} else {
if (child.field) {
$tableBody.find('tr').find('td[data-key$="' + child.key + '"]>div').prepend('<i style="cursor: pointer" class="childTable ' + icon[0] + '"></i>');
} else {
$tableBody.find('tr').find('td[data-key$="' + child.key + '"]>div').html('<i style="cursor: pointer" class="childTable ' + icon[0] + '"></i>');
}
}
$tableBody.children('tbody').children('tr').each(function () {
$(this).children('td:eq(' + curIndex + ')').find('.childTable').on('click', function (e) {
layui.stope(e)
var rowIndex = $(this).parents('tr:eq(0)').data('index'),
tableId = myTable.id,
key = $(this).parents('td:eq(0)').data('key'),
$this = $noFixedBody.children('tbody').children('tr[data-index=' + rowIndex + ']').children('td[data-key="' + key + '"]').find('.childTable:eq(0)'),
$fixedThis = $fixedBody.find('tr[data-index=' + rowIndex + ']').children('td[data-key="' + key + '"]').find('.childTable:eq(0)'),
data = table.cache[tableId][rowIndex],
children = child.children,
isTpl = false,
tplContent = '',
tr = $tableBody.children('tbody').children('tr[data-index="' + rowIndex + '"]'),
obj = {
data: data,
tr: tr,
del: function () {
table.cache[tableId][rowIndex] = [];
_this.destroyChildren(rowIndex, myTable, icon)
tr.remove();
table.resize(tableId);
},
update: function (fields) {
fields = fields || {};
layui.each(fields, function (key, value) {
if (key in data) {
var templet, td = tr.children('td[data-field="' + key + '"]');
data[key] = value;
table.eachCols(tableId, function (i, item2) {
if (item2.field == key && item2.templet) {
templet = item2.templet;
}
});
td.children('.layui-table-cell').html(function () {
return templet ? function () {
return typeof templet === 'function'
? templet(data)
: laytpl($(templet).html() || value).render(data)
}() : value;
}());
td.data('content', value);
}
});
},
close: function () {
_this.destroyChildren(rowIndex, myTable, icon)
table.resize(tableId);
}
};
if ($this.hasClass(icon[1])) {
if (typeof child.childClose === 'function') {
if (child.childClose(obj) === false) {
return;
}
}
} else {
// 展开事件
if (typeof child.childOpen === 'function') {
if (child.childOpen(obj) === false) {
return;
}
}
}
if (typeof children === 'function') {
children = children(data)
}
// 如果是 templet 自定义内容
if (typeof children === 'string') {
isTpl = true
tplContent = _this.parseTempData(child, child.field ? data[child.field] : null, data)
}
if (child.show === 2) { // 弹窗模式
child.layerOption ? (typeof child.layerOption.title === 'function' ? (child.layerOption.title = child.layerOption.title(data)) : null) : null;
layer.open($.extend({
type: 1,
title: '子表',
maxmin: true,
content: _this.getTables(this, data, child, myTable, children, isTpl, tplContent),
area: '1000px',
offset: '100px',
cancel: function () {
if (typeof child.childClose === 'function') {
if (child.childClose(obj) === false) {
return;
}
}
}
}, child.layerOption || {}));
if (!isTpl) {
_this.renderTable(this, data, child, myTable, children, icon);
}
} else { // 展开模式
// 开启手风琴模式
if (!$this.hasClass(icon[1]) && child.collapse) {
$tableBody.children('tbody').children('tr').children('td').find('.childTable').each(function () {
if ($(this).hasClass(icon[1])) {
_this.destroyChildren($(this).parents('tr:eq(0)').data('index'), myTable, icon)
}
})
}
// 多个入口时,关闭其他入口
if (!$this.hasClass(icon[1])) {
$this.parents('tr:eq(0)').children('td').find('.childTable').each(function () {
if ($(this).hasClass(icon[1])) {
$(this).removeClass(icon[1]).addClass(icon[0])
_this.destroyChildren($(this).parents('tr:eq(0)').data('index'), myTable, icon)
}
})
}
if ($this.hasClass(icon[1])) {
$this.removeClass(icon[1]).addClass(icon[0])
$fixedThis.removeClass(icon[1]).addClass(icon[0])
} else {
$this.removeClass(icon[0]).addClass(icon[1])
$fixedThis.removeClass(icon[0]).addClass(icon[1])
}
var rowspanIndex = $this.parents('td:eq(0)').attr("rowspan");
if ($this.hasClass(icon[1])) {
var newTr = [];
newTr.push('<tr data-tpl="' + isTpl + '" class="noHover childTr"><td colspan="' + $tableHead.find('th:visible').length + '" style="cursor: inherit; padding: 0;">');
newTr.push(_this.getTables(this, data, child, myTable, children, isTpl, tplContent));
newTr.push('</td></tr>');
if (rowspanIndex) {
var index = parseInt($this.parents('tr:eq(0)').data("index")) + parseInt(rowspanIndex) - 1;
$this.parents('table:eq(0)').children().children("[data-index='" + index + "']").after(newTr.join(''));
} else {
$this.parents('tr:eq(0)').after(newTr.join(''));
}
layui.element.init('tab')
if (!isTpl) {
_this.renderTable(this, data, child, myTable, children, icon);
// 阻止事件冒泡
$this.parents('tr:eq(0)').next().children('td').children('.layui-tab').children('.layui-tab-content').on('click', function (e) {
// 不阻止 tab 切换点击事件
if (!$(e.target.parentElement).hasClass('layui-tab-title')) {
e.stopPropagation()
}
}).off('dblclick').on('dblclick', function (e) {
e.stopPropagation()
}).on('mouseenter', 'td', function (e) {
e.stopPropagation()
}).on('change', function (e) {
layui.stope(e)
})
}
if ($fixedBody.length > 0) {
var $tr = $this.parents('tr:eq(0)').next(),
height = $tr.children('td').height(),
$patchDiv = '<div class="soul-table-child-patch" style="height: ' + height + 'px"></div>';
$tr.children('td').children('.soul-table-child-wrapper').css({
position: 'absolute',
top: 0,
width: '100%',
background: 'white',
'z-index': 200
})
$tr.children('td').append($patchDiv);
$fixedBody.find('tr[data-index="' + rowIndex + '"]').each(function () {
$(this).after('<tr><td style="padding: 0;" colspan="' + $(this).children('[data-key]').length + '">' + $patchDiv + '</td></tr>')
})
table.resize(tableId)
}
if (child.show === 3) {
$this.parents('tr:eq(0)').next().find('.layui-table-view').css({margin: 0, 'border-width': 0});
$this.parents('tr:eq(0)').next().find('.layui-table-header').css('display', 'none');
}
} else {
_this.destroyChildren(rowIndex, myTable, icon);
table.resize(tableId)
}
}
})
})
if (child.spread && child.show !== 2) {
$tableBody.children('tbody').children('tr').children('td').find('.childTable').trigger('click');
}
})()
}
}
},
/**
* 生成子表内容
* @param _this
* @param data
* @param child
* @param myTable
* @param children 子表配置
* @param isTpl 是否是自定义模版
* @param tplContent 自定义模版内容
* @returns {string}
*/
getTables: function (_this, data, child, myTable, children, isTpl, tplContent) {
var tables = [],
$table = $(myTable.elem),
$tableBox = $table.next().children('.layui-table-box'),
tableId = myTable.id,
rowTableId = tableId + $(_this).parents('tr:eq(0)').data('index'),
$tableHead = $tableBox.children('.layui-table-header').children('table'),
$tableMain = $table.next().children('.layui-table-box').children('.layui-table-body'),
$tableBody = $tableMain.children('table'),
scrollWidth = 0,
i;
if (isTpl) {
tables.push('<div class="soul-table-child-wrapper" style="margin: 0;border: 0;box-shadow: none;');
} else {
tables.push('<div class="layui-tab layui-tab-card soul-table-child-wrapper" lay-filter="table-child-tab-' + rowTableId + '" style="margin: 0;border: 0;box-shadow: none;');
}
if (child.show === 2) {
tables.push('max-width: ' + ($tableBody.width() - 2) + 'px">')
} else if (child.show === 3) {
//不限制宽度
tables.push('">')
} else {
if (child.childWidth === 'full') {
//不限制宽度
tables.push('">')
} else {
// 如果有滚动条
if ($tableMain.prop('scrollHeight') + (children.length > 0 ? children[0].height : 0) > $tableMain.height()) {
scrollWidth = this.getScrollWidth();
}
var maxWidth = $tableMain.width() - 1 - scrollWidth;
tables.push('max-width: ' + (maxWidth > $tableHead.width() ? $tableHead.width() : maxWidth) + 'px">')
}
}
if (isTpl) {
tables.push(tplContent)
} else {
if (child.show !== 3 && (typeof child.childTitle === 'undefined' || child.childTitle)) {
tables.push('<ul class="layui-tab-title">')
for (i = 0; i < children.length; i++) {
tables.push('<li class="' + (i === 0 ? 'layui-this' : '') + '">' + (typeof children[i].title === 'function' ? children[i].title(data) : children[i].title) + '</li>');
}
tables.push('</ul>')
}
if (child.show === 3) {
tables.push('<div class="layui-tab-content" style="padding: 0">');
} else {
tables.push('<div class="layui-tab-content" style="padding: 0 10px">');
}
for (i = 0; i < children.length; i++) {
var childTableId = rowTableId + i;
tables.push('<div class="layui-tab-item layui-show"><form action="" class="layui-form" ><table id="' + childTableId + '" lay-filter="' + childTableId + '"></table></form></div>');
}
tables.push('</div>');
}
tables.push('</div>');
return tables.join('')
},
/**
* 渲染子表
* @param _this
* @param data 父表当前行数据
* @param child 子表列
* @param myTable 父表配置
* @param children 子表配置
* @param icon 自定义图标
*/
renderTable: function (_this, data, child, myTable, children, icon) {
var tables = []
, _that = this
, tableId = myTable.id
, rowTableId = tableId + $(_this).parents('tr:eq(0)').data('index');
if (child.lazy) {
tables.push(renderChildTable(_that, _this, data, child, myTable, 0, children, icon));
} else {
for (var i = 0; i < children.length; i++) {
tables.push(renderChildTable(_that, _this, data, child, myTable, i, children, icon));
}
}
tableChildren[rowTableId] = tables;
layui.element.on('tab(table-child-tab-' + rowTableId + ')', function (tabData) {
if (child.lazy) {
var isRender = false; // 是否已经渲染
for (i = 0; i < tableChildren[rowTableId].length; i++) {
if (tableChildren[rowTableId][i].config.id === (rowTableId + tabData.index)) {
isRender = true;
break;
}
}
if (!isRender) {
tableChildren[rowTableId].push(renderChildTable(_that, _this, data, child, myTable, tabData.index, children))
}
}
var rowIndex = $(_this).parents('tr:eq(0)').data('index'),
height = $(tabData.elem).height();
$(_this).parents('.layui-table-box:eq(0)').children('.layui-table-body').children('table').children('tbody').children('tr[data-index=' + rowIndex + ']').next().children().children('.soul-table-child-patch').css('height', height)
$(_this).parents('.layui-table-box:eq(0)').children('.layui-table-fixed').children('.layui-table-body').children('table').children('tbody').children('tr[data-index=' + rowIndex + ']').next().children().children('.soul-table-child-patch').css('height', height)
table.resize(tableId)
});
function renderChildTable(_that, _this, data, child, myTable, i, children, icon) {
var param = _that.deepClone(children[i]), thisTableChild,
tableId = myTable.id,
rowIndex = $(_this).parents('tr:eq(0)').data('index'),
childTableId = tableId + rowIndex + i,
$table = $(myTable.elem),
$tableBox = $table.next().children('.layui-table-box'),
$tableBody = $.merge($tableBox.children('.layui-table-body').children('table'), $tableBox.children('.layui-table-fixed').children('.layui-table-body').children('table')),
tr = $tableBody.children('tbody').children('tr[data-index="' + rowIndex + '"]'),
row = table.cache[tableId][rowIndex],
// 父表当前行对象
pobj = {
data: row,
tr: tr,
del: function () {
table.cache[tableId][rowIndex] = [];
_that.destroyChildren(rowIndex, myTable, icon)
tr.remove();
table.resize(tableId);
},
update: function (fields) {
fields = fields || {};
layui.each(fields, function (key, value) {
if (key in row) {
var templet, td = tr.children('td[data-field="' + key + '"]');
row[key] = value;
table.eachCols(tableId, function (i, item2) {
if (item2.field == key && item2.templet) {
templet = item2.templet;
}
});
td.children('.layui-table-cell').html(function () {
return templet ? function () {
return typeof templet === 'function'
? templet(row)
: laytpl($(templet).html() || value).render(row)
}() : value;
}());
td.data('content', value);
}
});
},
close: function () {
_that.destroyChildren(rowIndex, myTable, icon)
table.resize(tableId);
}
};
param.id = childTableId;
param.elem = '#' + childTableId;
typeof param.where === 'function' && (param.where = param.where(data));
typeof param.data === 'function' && (param.data = param.data(data));
typeof param.url === 'function' && (param.url = param.url(data));
thisTableChild = table.render(param);
if (!child.lazy && i !== 0) {
$('#' + childTableId).parents('.layui-tab-item:eq(0)').removeClass('layui-show'); //解决隐藏时计算表格高度有问题
}
// 绑定 checkbox 事件
if (typeof param.checkboxEvent === 'function') {
table.on('checkbox(' + childTableId + ')', function (obj) {
param.checkboxEvent(_that.commonMember.call(this, _that, param, obj), pobj)
})
}
// 绑定 edit 事件
if (typeof param.editEvent === 'function') {
table.on('edit(' + childTableId + ')', function (obj) {
param.editEvent(_that.commonMember.call(this, _that, param, obj), pobj)
})
}
// 绑定 tool 事件
if (typeof param.toolEvent === 'function') {
table.on('tool(' + childTableId + ')', function (obj) {
param.toolEvent(_that.commonMember.call(this, _that, param, obj), pobj)
})
}
// 绑定 toolbar 事件
if (typeof param.toolbarEvent === 'function') {
table.on('toolbar(' + childTableId + ')', function (obj) {
param.toolbarEvent(_that.commonMember.call(this, _that, param, obj), pobj)
})
}
// 绑定单击行事件
if (typeof param.rowEvent === 'function') {
table.on('row(' + childTableId + ')', function (obj) {
param.rowEvent(_that.commonMember.call(this, _that, param, obj), pobj)
})
}
// 绑定双击行事件
if (typeof param.rowDoubleEvent === 'function') {
table.on('rowDouble(' + childTableId + ')', function (obj) {
param.rowDoubleEvent(_that.commonMember.call(this, _that, param, obj), pobj)
})
}
return thisTableChild;
}
},
destroyChildren: function (rowIndex, myTable, icon) {
var tableId = myTable.id,
$table = $(myTable.elem),
$tableBox = $table.next().children('.layui-table-box'),
$fixedBody = $tableBox.children('.layui-table-fixed').children('.layui-table-body').children('table'),
$tableBody = $.merge($tableBox.children('.layui-table-body').children('table'), $fixedBody),
$tr = $tableBody.children('tbody').children('tr[data-index="' + rowIndex + '"]'),
isTpl = $tr.next().data('tpl');
$tr.find('.childTable').removeClass(icon[1]).addClass(icon[0]);
// 暂时不处理 rowspan 情况
// var rowspanIndex = $this.parents('td:eq(0)').attr("rowspan");
// if(rowspanIndex){
// var index=$this.parents('tr:eq(0)').index()+parseInt(rowspanIndex);
// $this.parents('table:eq(0)').children().children('tr:eq('+index+')').remove()
// }else{
// $this.parents('tr:eq(0)').next().remove();
// }
$tr.next().remove()
if (isTpl === 'false') {
var tables = tableChildren[tableId + rowIndex];
if (layui.tableFilter) { //如果使用了筛选功能,同时清理筛选渲染的数据
layui.tableFilter.destroy(tables);
}
if (layui.soulTable) { // 清除记忆
for (var i = 0; i < tableChildren[tableId + rowIndex].length; i++) {
layui.soulTable.clearOriginCols(tableChildren[tableId + rowIndex][i].config.id)
}
}
}
delete tableChildren[tableId + rowIndex]
},
cloneJSON: function (obj) {
var JSON_SERIALIZE_FIX = {
PREFIX: "[[JSON_FUN_PREFIX_",
SUFFIX: "_JSON_FUN_SUFFIX]]"
};
var sobj = JSON.stringify(obj, function (key, value) {
if (typeof value === 'function') {
return JSON_SERIALIZE_FIX.PREFIX + value.toString() + JSON_SERIALIZE_FIX.SUFFIX;
}
return value;
});
return JSON.parse(sobj, function (key, value) {
if (typeof value === 'string' &&
value.indexOf(JSON_SERIALIZE_FIX.SUFFIX) > 0 && value.indexOf(JSON_SERIALIZE_FIX.PREFIX) === 0) {
return eval("(" + value.replace(JSON_SERIALIZE_FIX.PREFIX, "").replace(JSON_SERIALIZE_FIX.SUFFIX, "") + ")");
}
return value;
}) || {};
},
fixHoverStyle: function (myTable) {
var $table = $(myTable.elem)
, $tableBody = $table.next().children('.layui-table-box').children('.layui-table-body').children('table')
,
$tableFixed = $table.next().children('.layui-table-box').children('.layui-table-fixed').children('.layui-table-body').children('table')
, style = $table.next().find('style')[0],
sheet = style.sheet || style.styleSheet || {};
// 屏蔽掉layui原生 hover 样式
this.addCSSRule(sheet, '.layui-table-hover', 'background-color: inherit');
this.addCSSRule(sheet, '.layui-table-hover.soul-table-hover', 'background-color: #F2F2F2');
$.merge($tableFixed.children('tbody').children('tr'), $tableBody.children('tbody').children('tr'))
.on('mouseenter', function () {
var othis = $(this)
, index = $(this).data('index');
if (othis.data('off')) return;
$tableFixed.children('tbody').children('tr[data-index=' + index + ']').addClass(ELEM_HOVER);
$tableBody.children('tbody').children('tr[data-index=' + index + ']').addClass(ELEM_HOVER);
}).on('mouseleave', function () {
var othis = $(this)
, index = $(this).data('index');
if (othis.data('off')) return;
$tableFixed.children('tbody').children('tr[data-index=' + index + ']').removeClass(ELEM_HOVER);
$tableBody.children('tbody').children('tr[data-index=' + index + ']').removeClass(ELEM_HOVER);
})
},
addCSSRule: function (sheet, selector, rules, index) {
if ('insertRule' in sheet) {
sheet.insertRule(selector + '{' + rules + '}', index)
} else if ('addRule' in sheet) {
sheet.addRule(selector, rules, index)
}
},
// 深度克隆-不丢失方法
deepClone: function (obj) {
var newObj = Array.isArray(obj) ? [] : {}
if (obj && typeof obj === "object") {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
newObj[key] = (obj && typeof obj[key] === 'object') ? this.deepClone(obj[key]) : obj[key];
}
}
}
return newObj
},
getCompleteCols: function (origin) {
var cols = this.deepClone(origin);
var i, j, k, cloneCol;
for (i = 0; i < cols.length; i++) {
for (j = 0; j < cols[i].length; j++) {
if (!cols[i][j].exportHandled) {
if (cols[i][j].rowspan > 1) {
cloneCol = this.deepClone(cols[i][j])
cloneCol.exportHandled = true;
k = i + 1;
while (k < cols.length) {
cols[k].splice(j, 0, cloneCol)
k++
}
}
if (cols[i][j].colspan > 1) {
cloneCol = this.deepClone(cols[i][j])
cloneCol.exportHandled = true;
for (k = 1; k < cols[i][j].colspan; k++) {
cols[i].splice(j, 0, cloneCol)
}
j = j + parseInt(cols[i][j].colspan) - 1
}
}
}
}
return cols[cols.length - 1];
},
getScrollWidth: function (elem) {
var width = 0;
if (elem) {
width = elem.offsetWidth - elem.clientWidth;
} else {
elem = document.createElement('div');
elem.style.width = '100px';
elem.style.height = '100px';
elem.style.overflowY = 'scroll';
document.body.appendChild(elem);
width = elem.offsetWidth - elem.clientWidth;
document.body.removeChild(elem);
}
return width;
},
//解析自定义模板数据
parseTempData: function (item3, content, tplData, text) { //表头数据、原始内容、表体数据、是否只返回文本
var str = item3.children ? function () {
return typeof item3.children === 'function'
? item3.children(tplData)
: laytpl($(item3.children).html() || String(content)).render(tplData)
}() : content;
return text ? $('<div>' + str + '</div>').text() : str;
},
commonMember: function (_this, myTable, sets) {
var othis = $(this)
, tableId = myTable.id
, $table = $(myTable.elem)
, $tableBox = $table.next().children('.layui-table-box')
, $fixedBody = $tableBox.children('.layui-table-fixed').children('.layui-table-body').children('table')
, $tableBody = $.merge($tableBox.children('.layui-table-body').children('table'), $fixedBody)
, index = othis[0].tagName === 'TR' ? $(this).data('index') : othis.parents('tr:eq(0)').data('index')
, tr = $tableBody.children('tbody').children('tr[data-index="' + index + '"]')
, data = table.cache[tableId] || [];
data = data[index] || {};
return $.extend(sets, {
tr: tr //行元素
, oldValue: othis.prev() ? othis.prev().text() : null
, del: function () { //删除行数据
table.cache[tableId][index] = [];
tr.remove();
_this.scrollPatch(myTable);
}
, update: function (fields) { //修改行数据
fields = fields || {};
layui.each(fields, function (key, value) {
if (key in data) {
var templet, td = tr.children('td[data-field="' + key + '"]');
data[key] = value;
table.eachCols(tableId, function (i, item2) {
if (item2.field == key && item2.templet) {
templet = item2.templet;
}
});
td.children('.layui-table-cell').html(_this.parseTempData({
templet: templet
}, value, data));
td.data('content', value);
}
});
}
});
},
scrollPatch: function (myTable) {
var $table = $(myTable.elem),
layHeader = $table.next().children('.layui-table-box').children('.layui-table-header'),
layTotal = $table.next().children('.layui-table-total'),
layMain = $table.next().children('.layui-table-box').children('.layui-table-main'),
layFixed = $table.next().children('.layui-table-box').children('.layui-table-fixed'),
layFixRight = $table.next().children('.layui-table-box').children('.layui-table-fixed-r'),
layMainTable = layMain.children('table'),
scollWidth = layMain.width() - layMain.prop('clientWidth'),
scollHeight = layMain.height() - layMain.prop('clientHeight'),
outWidth = layMainTable.outerWidth() - layMain.width() //表格内容器的超出宽度
//添加补丁
, addPatch = function (elem) {
if (scollWidth && scollHeight) {
elem = elem.eq(0);
if (!elem.find('.layui-table-patch')[0]) {
var patchElem = $('<th class="layui-table-patch"><div class="layui-table-cell"></div></th>'); //补丁元素
patchElem.find('div').css({
width: scollWidth
});
elem.find('tr').append(patchElem);
}
} else {
elem.find('.layui-table-patch').remove();
}
}
addPatch(layHeader);
addPatch(layTotal);
//固定列区域高度
var mainHeight = layMain.height()
, fixHeight = mainHeight - scollHeight;
layFixed.find('.layui-table-body').css('height', layMainTable.height() >= fixHeight ? fixHeight : 'auto');
//表格宽度小于容器宽度时,隐藏固定列
layFixRight[outWidth > 0 ? 'removeClass' : 'addClass'](HIDE);
//操作栏
layFixRight.css('right', scollWidth - 1);
}
};
// 输出
exports('tableChild', mod);
});
/**
*
* @name: 表格筛选扩展
* @author: yelog
* @link: https://github.com/yelog/layui-soul-table
* @license: MIT
* @version: v1.6.4
*/
layui.define(['table', 'form', 'laydate', 'util', 'excel', 'laytpl'], function (exports) {
var $ = layui.jquery,
table = layui.table,
form = layui.form,
laydate = layui.laydate,
laytpl = layui.laytpl,
util = layui.util,
excel = layui.excel,
columnsTimeOut,
dorpListTimeOut,
conditionTimeOut,
bfColumnTimeOut,
bfCond1TimeOut,
isFilterReload = {},
SOUL_ROW_INDEX = 'SOUL_ROW_INDEX',
cache = {},
HIDE = 'layui-hide',
maxId = 1,
UNHANDLED_VALUES = [undefined, '', null],
where_cache = {},
isFilterCache = {},
table_cache = {},
conditionChangeItems = {
'eq': '等于',
'ne': '≠ 不等于',
'gt': '> 大于',
'ge': '≥ 大于等于',
'lt': '< 小于',
'le': '≤ 小于等于',
'contain': '包含',
'notContain': '不包含',
'start': '以...开头',
'end': '以...结尾',
'null': '为空',
'notNull': '不为空'
},
dateTimeItems = {
'all': '全部',
'yesterday': '昨天',
'thisWeek': '本周',
'lastWeek': '上周',
'thisMonth': '本月',
'thisYear': '今年'
},
defaultFilterItems = ['column', 'data', 'condition', 'editCondition', 'excel'],
itemsMap = {
'column': 'soul-column',
'data': 'soul-dropList',
'condition': 'soul-condition',
'editCondition': 'soul-edit-condition',
'excel': 'soul-export',
'clearCache': 'soul-clear-cache',
},
modeMapItems = {
'in': 'data',
'condition': 'condition',
'date': 'condition',
},
revertMode = {
'data': {
'mode': 'condition',
'type': 'eq',
'value': '',
},
'condition': {
'mode': 'in',
'values': [],
},
};
// 封装方法
var mod = {
/**
* 摧毁render数据
* @param myTables
*/
destroy: function (myTables) {
if (myTables) {
if (Array.isArray(myTables)) {
for (var i = 0; i < myTables.length; i++) {
deleteRender(myTables[i])
}
} else {
deleteRender(myTables);
}
}
function deleteRender(myTable) {
if (!myTable) {
return;
}
var tableId = myTable.config.id;
$('#soul-filter-list' + tableId).remove();
$('#soulCondition' + tableId).remove();
$('#soulDropList' + tableId).remove();
delete isFilterReload[tableId];
delete where_cache[tableId];
delete table_cache[tableId];
}
},
clearFilter: function (myTable) {
if (typeof myTable === 'string') {
myTable = table_cache[myTable]
}
if (!where_cache[myTable.id] || !where_cache[myTable.id].filterSos || where_cache[myTable.id].filterSos === "[]") {
return;
}
where_cache[myTable.id].filterSos = "[]"
this.soulReload(myTable, true)
if (table_cache[myTable.id].where && table_cache[myTable.id].where.filterSos && table_cache[myTable.id].where.filterSos !== "[]") {
table_cache[myTable.id].where.filterSos = "[]"
}
},
render: function (myTable) {
var _this = this,
$table = $(myTable.elem),
$tableMain = $table.next().children('.layui-table-box').children('.layui-table-main'),
$tableHead = $table.next().children('.layui-table-box').children('.layui-table-header').children('table'),
$fixedLeftTableHead = $table.next().children('.layui-table-box').children('.layui-table-fixed-l').children('.layui-table-header').children('table'),
$fixedRigthTableHead = $table.next().children('.layui-table-box').children('.layui-table-fixed-r').children('.layui-table-header').children('table'),
tableId = myTable.id,
columns = _this.getCompleteCols(myTable.cols),
filterItems = myTable.filter ? myTable.filter.items || defaultFilterItems : defaultFilterItems,
needFilter = false, // 是否存在筛选列需要进行初始化
initFilter = false, // 是否为第一次筛选
mainExcel = typeof myTable.excel === 'undefined' || ((myTable.excel && (typeof myTable.excel.on === 'undefined' || myTable.excel.on)) ? myTable.excel : false),
i, j;
for (i = 0; i < columns.length; i++) {
if (columns[i].field && columns[i].filter) {
needFilter = true;
if ($tableHead.find('th[data-field="' + columns[i].field + '"]').children().children('.soul-table-filter').length === 0) {
initFilter = true;
if ($tableHead.find('th[data-field="' + columns[i].field + '"]').children().children('.layui-table-sort').length > 0) {
$tableHead.find('th[data-field="' + columns[i].field + '"]').children().children('.layui-table-sort').hide()
$tableHead.find('th[data-field="' + columns[i].field + '"]').children().append('<span class="layui-table-sort soul-table-filter layui-inline" data-items="' + (columns[i].filter.items ? columns[i].filter.items.join(',') : '') + '" data-column="' + columns[i].field + '" lay-sort="' + $tableHead.find('th[data-field="' + columns[i].field + '"]').children().children('.layui-table-sort').attr('lay-sort') + '" ' + (typeof columns[i].filter.split === 'undefined' ? '' : 'data-split="' + columns[i].filter.split + '"') + '><i class="soul-icon soul-icon-filter"></i><i class="soul-icon soul-icon-filter-asc"></i><i class="soul-icon soul-icon-filter-desc"></i></span>')
} else {
$tableHead.find('th[data-field="' + columns[i].field + '"]').children().append('<span class="soul-table-filter layui-inline" data-items="' + (columns[i].filter.items ? columns[i].filter.items.join(',') : '') + '" data-column="' + columns[i].field + '" ' + (typeof columns[i].filter.split === 'undefined' ? '' : 'data-split="' + columns[i].filter.split + '"') + '><i class="soul-icon soul-icon-filter"></i><i class="soul-icon soul-icon-filter-asc"></i><i class="soul-icon soul-icon-filter-desc"></i></span>')
}
if ($fixedLeftTableHead.find('th[data-field="' + columns[i].field + '"]').children().children('.layui-table-sort').length > 0) {
$fixedLeftTableHead.find('th[data-field="' + columns[i].field + '"]').children().children('.layui-table-sort').hide()
$fixedLeftTableHead.find('th[data-field="' + columns[i].field + '"]').children().append('<span class="layui-table-sort soul-table-filter layui-inline" data-items="' + (columns[i].filter.items ? columns[i].filter.items.join(',') : '') + '" data-column="' + columns[i].field + '" lay-sort="' + $fixedLeftTableHead.find('th[data-field="' + columns[i].field + '"]').children().children('.layui-table-sort').attr('lay-sort') + '" ' + (typeof columns[i].filter.split === 'undefined' ? '' : 'data-split="' + columns[i].filter.split + '"') + '><i class="soul-icon soul-icon-filter"></i><i class="soul-icon soul-icon-filter-asc"></i><i class="soul-icon soul-icon-filter-desc"></i></span>')
} else {
$fixedLeftTableHead.find('th[data-field="' + columns[i].field + '"]').children().append('<span class="soul-table-filter layui-inline" data-items="' + (columns[i].filter.items ? columns[i].filter.items.join(',') : '') + '" data-column="' + columns[i].field + '" ' + (typeof columns[i].filter.split === 'undefined' ? '' : 'data-split="' + columns[i].filter.split + '"') + '><i class="soul-icon soul-icon-filter"></i><i class="soul-icon soul-icon-filter-asc"></i><i class="soul-icon soul-icon-filter-desc"></i></span>')
}
if ($fixedRigthTableHead.find('th[data-field="' + columns[i].field + '"]').children().children('.layui-table-sort').length > 0) {
$fixedRigthTableHead.find('th[data-field="' + columns[i].field + '"]').children().children('.layui-table-sort').hide()
$fixedRigthTableHead.find('th[data-field="' + columns[i].field + '"]').children().append('<span class="layui-table-sort soul-table-filter layui-inline" data-items="' + (columns[i].filter.items ? columns[i].filter.items.join(',') : '') + '" data-column="' + columns[i].field + '" lay-sort="' + $fixedRigthTableHead.find('th[data-field="' + columns[i].field + '"]').children().children('.layui-table-sort').attr('lay-sort') + '" ' + (typeof columns[i].filter.split === 'undefined' ? '' : 'data-split="' + columns[i].filter.split + '"') + '><i class="soul-icon soul-icon-filter"></i><i class="soul-icon soul-icon-filter-asc"></i><i class="soul-icon soul-icon-filter-desc"></i></span>')
} else {
$fixedRigthTableHead.find('th[data-field="' + columns[i].field + '"]').children().append('<span class="soul-table-filter layui-inline" data-items="' + (columns[i].filter.items ? columns[i].filter.items.join(',') : '') + '" data-column="' + columns[i].field + '" ' + (typeof columns[i].filter.split === 'undefined' ? '' : 'data-split="' + columns[i].filter.split + '"') + '><i class="soul-icon soul-icon-filter"></i><i class="soul-icon soul-icon-filter-asc"></i><i class="soul-icon soul-icon-filter-desc"></i></span>')
}
}
}
}
table_cache[myTable.id] = myTable // 缓存table配置
isFilterCache[myTable.id] = needFilter;
if (!needFilter) {
// 缓存所有数据
if (myTable.url && !myTable.page) {
// 修复不分页时,前端筛选后,data不为空,造成所有数据丢失的问题
cache[myTable.id] = layui.table.cache[myTable.id]
} else {
cache[myTable.id] = myTable.data || layui.table.cache[myTable.id]
}
return;
} //如果没筛选列,直接退出
// 渲染底部筛选条件
if (!(myTable.filter && typeof myTable.filter.bottom !== 'undefined' && !myTable.filter.bottom) && $table.next().children('.soul-bottom-contion').length === 0) {
$table.next().children('.layui-table-box').after('<div class="soul-bottom-contion"><div class="condition-items"></div><div class="editCondtion"><a class="layui-btn layui-btn-primary">编辑筛选条件</a></div></div>')
var changeHeight = $table.next().children('.layui-table-box').children('.layui-table-body').outerHeight() - $table.next().children('.soul-bottom-contion').outerHeight();
if (myTable.page && $table.next().children('.layui-table-page').hasClass('layui-hide')) {
changeHeight += $table.next().children('.layui-table-page').outerHeight()
}
$table.next().children('.layui-table-box').children('.layui-table-body').css('height', changeHeight)
var fixHeight = changeHeight - _this.getScrollWidth($tableMain[0]),
layMainTableHeight = $tableMain.children('table').height()
$table.next().children('.layui-table-box').children('.layui-table-fixed').children('.layui-table-body').css('height', layMainTableHeight >= fixHeight ? fixHeight : 'auto')
$table.next().children('.soul-bottom-contion').children('.condition-items').css('width', ($table.next().children('.soul-bottom-contion').width() - $table.next().children('.soul-bottom-contion').children('.editCondtion').width()) + 'px');
$table.next().children('.soul-bottom-contion').children('.editCondtion').children('a').on('click', function () {
_this.showConditionBoard(myTable);
})
}
/**
* 不重载表头数据,重新绑定事件后结束
*/
if (!initFilter || isFilterReload[myTable.id] || myTable.isSoulFrontFilter) {
isFilterReload[myTable.id] = false
myTable['isSoulFrontFilter'] = false
// 同步选中状态
if (!myTable.url && myTable.page && myTable.data) {
myTable.data.forEach(function (row) {
for (i = 0; i < cache[myTable.id].length; i++) {
if (cache[myTable.id][i][SOUL_ROW_INDEX] === row[SOUL_ROW_INDEX]) {
cache[myTable.id][i] = row
break;
}
}
})
}
this.bindFilterClick(myTable);
return;
} else {
if (!myTable.url && myTable.page && myTable.data && myTable.data.length > myTable.limit) {
// 前端分页大于一页,修复 index (用于排序恢复时需要通过这个排序)
layui.each(myTable.data, function (index, item) {
item[myTable.indexName] = index;
})
}
/**
* 缓存所有数据
*/
if (myTable.url && !myTable.page) {
// 修复不分页时,前端筛选后,data不为空,造成所有数据丢失的问题
cache[myTable.id] = layui.table.cache[myTable.id]
} else {
cache[myTable.id] = myTable.data || layui.table.cache[myTable.id]
}
// 给表格数据添加位置标志
cache[myTable.id].forEach(function (item, index) {
item[SOUL_ROW_INDEX] = index
})
if (myTable.filter && myTable.filter.clearFilter) {
if (myTable.where && myTable.where.filterSos && JSON.parse(myTable.where.filterSos).length > 0) {
// 重新查询新数据
myTable.where.filterSos = '[]';
where_cache[myTable.id] = myTable.where || {}
_this.soulReload(myTable, false);
return;
} else {
where_cache[myTable.id] = myTable.where || {}
}
} else if ((typeof myTable.url !== 'undefined' && myTable.page ? typeof myTable.where.filterSos === 'undefined' : true) && where_cache[myTable.id] && JSON.parse(where_cache[myTable.id].filterSos || '[]').length > 0) {
myTable.where['filterSos'] = where_cache[myTable.id].filterSos
where_cache[myTable.id] = myTable.where;
_this.soulReload(myTable, false);
return;
} else {
where_cache[myTable.id] = myTable.where || {}
}
}
// 第一次渲染时,追加数据
if ($('#soul-filter-list' + tableId).length === 0) {
if (typeof myTable.soulSort === 'undefined' || myTable.soulSort) {
if (typeof $table.attr('lay-filter') === 'undefined') {
$table.attr('lay-filter', tableId);
}
table.on('sort(' + $table.attr('lay-filter') + ')', function (obj) {
// 同步分页信息
myTable.limit = table_cache[myTable.id].limit
if (myTable.url && myTable.page) {
// 后台分页
where_cache[myTable.id].field = obj.field;
where_cache[myTable.id].order = obj.type;
isFilterReload[myTable.id] = true;
table.render($.extend(myTable, {
initSort: obj
, where: where_cache[myTable.id]
, page: {
curr: 1 //重新从第 1 页开始
}
}));
} else if (!myTable.url && myTable.page) {
// 前台分页
if (obj.type === 'asc') { //升序
cache[myTable.id] = layui.sort(cache[myTable.id], obj.field)
} else if (obj.type === 'desc') { //降序
cache[myTable.id] = layui.sort(cache[myTable.id], obj.field, true)
} else { //清除排序
cache[myTable.id] = layui.sort(cache[myTable.id], myTable.indexName)
}
myTable.initSort = obj;
myTable.page = {curr: 1};
_this.soulReload(myTable, false)
}
});
}
var soulFilterList = [],
filterItemsHtml = {
column: '<li class="soul-column"><i class="layui-icon layui-icon-table"></i> 表格列 <i class="layui-icon layui-icon-right" style="float: right"></i></li>',
data: '<li class="soul-dropList"><i class="soul-icon soul-icon-drop-list"></i> 筛选数据 <i class="layui-icon layui-icon-right" style="float: right"></i></li>',
condition: '<li class="soul-condition"><i class="soul-icon soul-icon-query"></i> 筛选条件 <i class="layui-icon layui-icon-right" style="float: right"></i></li>',
editCondition: '<li class="soul-edit-condition"><i class="layui-icon layui-icon-edit"></i> 编辑筛选条件 </li>',
excel: '<li class="soul-export"><i class="soul-icon soul-icon-download"></i> 导出excel </li>',
clearCache: '<li class="soul-clear-cache"><i class="layui-icon layui-icon-delete"></i> 清除缓存 </li>'
};
soulFilterList.push('<div id="soul-filter-list' + tableId + '"><form action="" class="layui-form" lay-filter="orm"><ul id="main-list' + tableId + '" style="display: none">');
soulFilterList.push('<li class="soul-sort" data-value="asc" ><i class="soul-icon soul-icon-asc"></i> 升序排列 </li>');
soulFilterList.push('<li class="soul-sort" data-value="desc" style="border-bottom: 1px solid #e6e6e6"><i class="soul-icon soul-icon-desc"></i> 降序排列 </li>');
for (i = 0; i < defaultFilterItems.length; i++) {
if (defaultFilterItems[i] === 'excel' && !mainExcel) {
continue
}
soulFilterList.push(filterItemsHtml[defaultFilterItems[i]]);
}
soulFilterList.push('</ul><ul id="soul-columns' + tableId + '" style="display: none;">');
var types = {}; //存储过滤数据的类型
// 根据表格列显示
for (i = 0; i < columns.length; i++) {
if (columns[i].type === 'checkbox' || !columns[i].field) {
soulFilterList.push('<li class="layui-hide"><input type="checkbox" title="' + columns[i].title + '" /></li>')
continue;
}
soulFilterList.push('<li data-value="' + columns[i].field + '" data-key="' + i + '"><input type="checkbox" value="' + (myTable.index + '-' + columns[i].key) + '" title="' + columns[i].title + '" data-fixed="' + (columns[i].fixed || "") + '" lay-skin="primary" lay-filter="changeColumns' + tableId + '" ' + (columns[i].hide ? '' : 'checked') + '></li>');
//存储过滤数据的类型
if (columns[i].filter && columns[i].filter.type) {
if (columns[i].filter.field) {
types[columns[i].filter.field] = columns[i].filter.type;
} else {
types[columns[i].field] = columns[i].filter.type;
}
}
}
if (JSON.stringify(types).length !== 2) {
myTable.where['tableFilterType'] = JSON.stringify(types);
}
soulFilterList.push('</ul><div id="soul-dropList' + tableId + '" style="display: none"><div class="filter-search"><input type="text" placeholder="关键字搜索" class="layui-input"></div><div class="check"><div class="multiOption" data-type="all"><i class="soul-icon">&#xe623;</i> 全选</div><div class="multiOption" data-type="none"><i class="soul-icon">&#xe63e;</i> 清空</div><div class="multiOption" data-type="reverse"><i class="soul-icon">&#xe614;</i>反选</div></div><ul></ul></div>');
soulFilterList.push('<ul id="soul-condition' + tableId + '" style="display: none;"></ul></form></div>');
$('body').append(soulFilterList.join(''));
// 显示隐藏列
var liClick = true;
form.on('checkbox(changeColumns' + tableId + ')', function (data) {
liClick = false;
var columnkey = data.value
if (data.elem.checked) {
$table.next().find('[data-key=' + columnkey + ']').removeClass(HIDE);
} else {
$table.next().find('[data-key=' + columnkey + ']').addClass(HIDE);
}
// 同步配置
for (i = 0; i < myTable.cols.length; i++) {
for (j = 0; j < myTable.cols[i].length; j++) {
if ((myTable.index + '-' + myTable.cols[i][j].key) === columnkey) {
myTable.cols[i][j]['hide'] = !data.elem.checked
}
}
}
if (layui.soulTable) {
layui.soulTable.fixTableRemember(myTable)
}
$table.next().children('.layui-table-box').children('.layui-table-body').children('table').children('tbody').children('tr.childTr').children('td').attr('colspan', $table.next().children('.layui-table-box').children('.layui-table-header').find('thead>tr>th:visible').length)
table.resize(tableId)
});
$('#soul-columns' + tableId + '>li[data-value]').on('click', function () {
if (!$(this).find(':checkbox').is(':disabled')) { //disabled禁止点击
if (liClick) {
$(this).find('div.layui-form-checkbox').trigger('click');
}
liClick = true;
}
});
// 全选-反选事件
$('#soul-dropList' + tableId + ' .check [data-type]').on('click', function () {
switch ($(this).data('type')) {
case 'all':
$(this).parents('#soul-dropList' + tableId).find('input[type=checkbox]:not(:checked)').prop('checked', true);
break;
case 'reverse':
$(this).parents('#soul-dropList' + tableId).find('input[type=checkbox]').each(function () {
$(this).prop('checked', !$(this).prop('checked'))
});
break;
case 'none':
$(this).parents('#soul-dropList' + tableId).find('input[type=checkbox]:checked').prop('checked', false);
break;
}
form.render('checkbox', 'orm');
_this.updateDropList(myTable, $('#main-list' + tableId).data('field'));
return false;
});
// 关键字搜索
$('#soul-dropList' + tableId + ' .filter-search input').on('input', function () {
var key = $(this).val();
if (key === '') {
$('#soul-dropList' + tableId + '>ul>li').show();
} else {
$('#soul-dropList' + tableId + '>ul>li').hide();
$('#soul-dropList' + tableId + '>ul>li[data-value*="' + key.toLowerCase() + '"]').show();
}
})
// 显示表格列
$('#main-list' + tableId + ' .soul-column').on('mouseover', function (e) {
_this.hideDropList(myTable);
_this.hideCondition(myTable);
e.stopPropagation();
if (columnsTimeOut) {
clearTimeout(columnsTimeOut)
}
columns = _this.getCompleteCols(myTable.cols)
for (i = 0; i < columns.length; i++) {
$('#soul-columns' + tableId).find('li[data-value="' + columns[i].field + '"]>input').prop('checked', !columns[i].hide);
}
form.render('checkbox', 'orm');
$('#soul-columns' + tableId).show();
var left, animate;
if ($(this).parent().offset().left + $(this).parent().width() + $('#soul-columns' + tableId).width() < document.body.clientWidth) {
left = $(this).parent().offset().left + $(this).parent().width();
animate = 'fadeInLeft'
} else {
left = $(this).parent().offset().left - $('#soul-columns' + tableId).width();
animate = 'fadeInRight'
}
$('#soul-columns' + tableId).css({'top': $(this).offset().top, 'left': left})
.removeClass().addClass(animate + ' animated');
});
// 显示数据下拉
$('#main-list' + tableId + ' .soul-dropList').on('mouseover', function (e) {
if ($('#soul-dropList' + tableId).is(':visible') && !$('#soul-dropList' + tableId).hasClass('fadeOutLeft')) {
return false;
}
_this.hideColumns(myTable);
_this.hideCondition(myTable);
e.stopPropagation();
if (dorpListTimeOut) {
clearTimeout(dorpListTimeOut);
}
$('#soul-dropList' + tableId + '>.filter-search>input').val('');
$('#soul-dropList' + tableId).show();
var left, animate, field = $('#main-list' + tableId).data('field');
if ($('#main-list' + tableId).offset().left + $('#soul-dropList' + tableId).width() + $('#soul-dropList' + tableId).width() < document.body.clientWidth) {
left = $('#main-list' + tableId).offset().left + $('#main-list' + tableId).width();
animate = 'fadeInLeft';
} else {
left = $('#main-list' + tableId).offset().left - $('#soul-dropList' + tableId).width();
animate = 'fadeInRight';
}
$('#soulDropList' + tableId).find('.' + field + 'DropList li input[type=checkbox]:checked').prop('checked', false);
var where = where_cache[myTable.id] || {},
filterSos = JSON.parse(where.filterSos ? where.filterSos : null),
id = '', prefix = '';
if (filterSos) {
for (i = 0; i < filterSos.length; i++) {
if (filterSos[i].head && filterSos[i].mode === "in" && filterSos[i].field === field) {
id = filterSos[i].id;
prefix = filterSos[i].prefix;
for (j = 0; j < filterSos[i].values.length; j++) {
$('#soulDropList' + tableId).find('.' + field + 'DropList li input[type=checkbox][value="' + filterSos[i].values[j] + '"]').prop('checked', true);
}
break;
}
}
}
$('#soul-dropList' + tableId + '>ul').data({
head: true,
'id': id,
prefix: prefix,
refresh: true,
split: $('#main-list' + tableId).data('split')
}).html($('#soulDropList' + tableId).find('.' + field + 'DropList li').clone());
$('#soul-dropList' + tableId).css({'top': $(this).offset().top, 'left': left})
.show().removeClass().addClass(animate + ' animated');
setTimeout(function () {
$('#soul-dropList' + tableId + '>.filter-search>input').focus() // 聚焦搜索框
form.render('checkbox', 'orm');
}, 1);
// 监听筛选数据
var liClick = true;
form.on('checkbox(soulDropList' + tableId + ')', function (data) {
liClick = false;
_this.updateDropList(myTable, field);
});
$('#soul-dropList' + tableId + '>ul>li[data-value]').on('click', function () {
if (liClick) {
$(this).find('div.layui-form-checkbox').trigger('click');
}
liClick = true;
})
});
// 显示筛选条件
$('#main-list' + tableId + ' .soul-condition').on('mouseover', function (e) {
if ($('#soul-condition' + tableId).is(':visible') && !$('#soul-condition' + tableId).hasClass('fadeOutLeft')) {
return false;
}
_this.hideColumns(myTable);
_this.hideDropList(myTable);
e.stopPropagation();
if (conditionTimeOut) {
clearTimeout(conditionTimeOut);
}
var documentWidth = document.body.clientWidth;
$('#soul-condition' + tableId).show();
var left, animate, field = $(this).parent().data('field');
if ($(this).parent().offset().left + $(this).parent().width() + $('#soul-condition' + tableId).width() < documentWidth) {
left = $(this).parent().offset().left + $(this).parent().width();
animate = 'fadeInLeft'
} else {
left = $(this).parent().offset().left - $('#soul-condition' + tableId).width();
animate = 'fadeInRight'
}
var filterSo, conditionHtml = [],
where = where_cache[myTable.id] || {},
filterSos = JSON.parse(where.filterSos ? where.filterSos : null);
if (filterSos) {
for (i = 0; i < filterSos.length; i++) {
if (filterSos[i].head && filterSos[i].field === field && (filterSos[i].mode === "date" || filterSos[i].mode === 'group')) {
filterSo = filterSos[i]
break;
}
}
}
var filterType = $(this).parent().data('type');
if (_this.startsWith(filterType, 'date')) {
_this.showDate(myTable, field, filterSo, animate, $(this).offset().top, $(this).parent().offset().left + $(this).parent().width(), 'down', true);
} else {
/**
* 筛选条件
*/
var fieldMap = {};
for (i = 0; i < columns.length; i++) {
if (columns[i].field) {
fieldMap[columns[i]['field']] = columns[i]
}
}
// 查询条件
var selectStr = "<select lay-filter='conditionChange'>";
for (var key in conditionChangeItems) {
selectStr += '<option value="' + key + '">' + conditionChangeItems[key] + '</option>';
}
selectStr += "</select>";
conditionHtml.push('<table class="condition-table"><tbody>');
if (filterSo && filterSo.children && filterSo.children.length > 0) {
for (i = 0; i < filterSo.children.length; i++) {
var id = filterSo.children[i].id,
prefix = filterSo.children[i].prefix,
type = filterSo.children[i].type,
value = filterSo.children[i].value;
conditionHtml.push('<tr data-id="' + id + '">');
if (i === 0) {
conditionHtml.push('<td class="soul-condition-title">' + fieldMap[field].title + '</td>')
} else {
conditionHtml.push(
'<td>' +
' <div>' +
' <input type="checkbox" name="switch" lay-filter="soul-coondition-switch" lay-skin="switch" lay-text="与|或" ' + (!prefix || prefix === 'and' ? 'checked' : '') + '>' +
' </div>' +
'</td>')
}
conditionHtml.push('<td style="width: 110px;"><div class="layui-block" ><select lay-filter="conditionChange">');
for (var key in conditionChangeItems) {
conditionHtml.push('<option value="' + key + '" ' + (key === type ? 'selected' : '') + '>' + conditionChangeItems[key] + '</option>');
}
conditionHtml.push('</select></div></td>')
conditionHtml.push('<td style="width: 110px;"><div class="layui-block" ><input class="layui-input value" value="' + (value || '') + '" placeholder="值" /></div></td>');
conditionHtml.push('<td><i class="layui-icon layui-icon-delete del" style="font-size: 23px; color: #FF5722; cursor: pointer"></i></td>');
conditionHtml.push('</tr>')
}
} else {
conditionHtml.push('<tr data-id="" data-type="eq" data-value="">'
+ '<td class="soul-condition-title">' + fieldMap[field].title + '</td>'
+ '<td style="width: 110px;"><div class="layui-block" >' + selectStr
+ '</div></td>'
+ '<td style="width: 110px;"><div class="layui-block" ><input class="layui-input value" placeholder="值" /></div></td>'
+ '<td><i class="layui-icon layui-icon-delete del" style="font-size: 23px; color: #FF5722; cursor: pointer"></i></td>'
+ '</tr>');
}
conditionHtml.push('</tbody></table><div style="text-align: center; padding-top: 5px"><button class="layui-btn layui-btn-sm" data-type="add"><i class="layui-icon">&#xe654;</i>添加</button><span style="display: inline-block;width: 50px"></span><button class="layui-btn layui-btn-sm" data-type="search"><i class="layui-icon">&#xe615;</i>查询</button></div>')
$('#soul-condition' + tableId).data({head: true, id: filterSo ? filterSo.id || '' : ''})
.html(conditionHtml.join(''))
.css({'top': $(this).offset().top, 'left': left})
.show().removeClass().addClass(animate + ' animated');
$('.condition-table').on('click', function () {
return false;
})
// 新增与查询
$('#soul-condition' + tableId + ' button[data-type]').on('click', function () {
/**
* 新增
*/
if ($(this).data('type') === 'add') {
var groupId = $('#soul-condition' + tableId).data('id'),
head = $('#soul-condition' + tableId).data('head'),
type = 'eq',
filterSo,
$tr1 = $('#soul-condition' + tableId).find('tr:eq(0)');
if (groupId) {
filterSo = {
head: head,
prefix: 'and',
field: field,
mode: 'condition',
type: type,
value: '',
groupId: groupId
}
} else {
filterSo = {
head: head,
prefix: head ? 'and' : 'and',
mode: 'group',
field: field,
children: [{
id: _this.getDifId(),
prefix: 'and',
field: field,
mode: 'condition',
type: $tr1.find('select').val(),
value: $tr1.find('.value').val()
}, {
id: _this.getDifId(),
prefix: 'and',
field: field,
mode: 'condition',
type: type,
value: ''
}]
}
}
_this.updateWhere(myTable, filterSo);
if (!groupId) {
$('#soul-condition' + tableId).data('id', filterSo.id);
$tr1.data('id', filterSo.children[0].id);
}
// $tableHead.find('thead>tr>th[data-field="'+field+'"] .soul-table-filter').attr('soul-filter','true');
var newId = groupId ? filterSo.id : filterSo.children[1].id;
var newTr = '<tr data-id="' + newId + '"><td>' +
' <div>' +
' <input type="checkbox" name="switch" lay-filter="soul-coondition-switch" lay-skin="switch" lay-text="与|或" checked>' +
' </div>' +
'</td>'
+ '<td style="width: 110px;"><div class="layui-block">' + selectStr + '</div></td>'
+ '<td style="width: 110px;"><div class="layui-block"><input class="layui-input value" placeholder="值" /></div></td>'
+ '<td><i class="layui-icon layui-icon-delete del" style="font-size: 23px; color: #FF5722; cursor: pointer"></i></td></tr>';
$('#soul-condition' + tableId + ">table>tbody").append(newTr)
$('#soul-condition' + tableId).find('.del:last').on('click', function () { //删除
delCurrentTr(this)
});
// input同步筛选条件
$('#soul-condition' + tableId + ' input.value:last').on('input', function () {
updateTrWhere($(this).parents('tr:eq(0)'))
});
} else if ($(this).data('type') === 'search') {
/**
* 查询
*/
_this.soulReload(myTable);
}
form.render('select', 'orm');
form.render('checkbox', 'orm');
return false;
});
// input同步筛选条件
$('#soul-condition' + tableId + ' input.value').on('input', function () {
updateTrWhere($(this).parents('tr:eq(0)'));
});
// 当前行改动时,同步where条件
function updateTrWhere($tr) {
var id = $tr.data('id'),
groupId = $('#soul-condition' + tableId).data('id'),
prefix = $tr.find('input[lay-filter="soul-coondition-switch"]:checked').prop('checked') ? 'and' : 'or',
type = $tr.find('select').val(),
value = $tr.find('.value').val(),
head = $('#soul-condition' + tableId).data('head');
if (groupId) {
filterSo = {
id: id,
prefix: prefix,
mode: 'condition',
field: field,
type: type,
value: value,
groupId: groupId
}
} else {
filterSo = {
head: head,
prefix: head ? 'and' : 'and',
mode: 'group',
field: field,
children: [{
id: _this.getDifId(),
prefix: prefix,
mode: 'condition',
field: field,
type: type,
value: value,
groupId: groupId
}]
}
}
_this.updateWhere(myTable, filterSo)
if (!groupId) {
$('#soul-condition' + tableId).data('id', filterSo.id);
$tr.data('id', filterSo.children[0].id)
} else if (!id) {
$tr.data('id', filterSo.id);
}
}
// select同步筛选条件
form.on('select(conditionChange)', function (data) {
if (data.value === 'null' || data.value === 'notNull') {
$(this).parents('tr').find('input.value').hide();
} else {
$(this).parents('tr').find('input.value').show();
}
updateTrWhere($(data.elem).parents('tr:eq(0)'));
})
// radio同步筛选条件
form.on('switch(soul-coondition-switch)', function (data) {
updateTrWhere($(this).parents('tr:eq(0)'));
});
// 删除当前行
$('#soul-condition' + tableId + ' .del').on('click', function () {
delCurrentTr(this)
});
function delCurrentTr(obj) {
var id;
if ($(obj).parents('table:eq(0)').find('tr').length === 1) {
id = $('#soul-condition' + tableId).data('id');
$('#soul-condition' + tableId).data('id', '');
$(obj).parents('tr:eq(0)').find('select').val('eq')
$(obj).parents('tr:eq(0)').find('.value').val('').show()
form.render('select', 'orm');
} else {
id = $(obj).parents('tr:eq(0)').data('id');
if ($(obj).parents('tr:eq(0)').index() === 0) {
$(obj).parents('table:eq(0)').find('tr:eq(1)>td:eq(0)').html(fieldMap[field].title).addClass('soul-condition-title')
}
$(obj).parents('tr:eq(0)').remove()
}
if (id) {
_this.updateWhere(myTable, {
id: id,
delete: true
})
}
}
}
form.render('select', 'orm');
form.render('checkbox', 'orm');
});
$('#soul-columns' + tableId + ', #soul-dropList' + tableId).on('mouseover', function (e) {
e.stopPropagation();
});
$('#main-list' + tableId + ' .soul-edit-condition').on('mouseover', function (e) {
_this.hideColumns(myTable)
_this.hideDropList(myTable)
_this.hideCondition(myTable)
e.stopPropagation();
}).on('click', function () {
$('#main-list' + tableId).hide();
_this.showConditionBoard(myTable)
});
$('#main-list' + tableId + ' .soul-export').on('mouseover', function (e) {
_this.hideColumns(myTable)
_this.hideDropList(myTable)
_this.hideCondition(myTable)
e.stopPropagation();
}).on('click', function () {
$('#main-list' + tableId).hide();
_this.export(table_cache[myTable.id])
});
$('#main-list' + tableId + ' .soul-clear-cache').on('mouseover', function (e) {
_this.hideColumns(myTable)
_this.hideDropList(myTable)
_this.hideCondition(myTable)
e.stopPropagation();
}).on('click', function () {
$('#main-list' + tableId).hide();
if (layui.soulTable) {
layui.soulTable.clearCache(myTable)
}
layer.msg('已还原!', {icon: 1, time: 1000})
});
$('#main-list' + tableId).on('mouseover', function (e) {
var curX = e.pageX;
var curY = e.pageY;
var div = $(this);
var y1 = div.offset().top; //div上面两个的点的y值
var y2 = y1 + div.height();//div下面两个点的y值
var x1 = div.offset().left; //div左边两个的点的x值
var x2 = x1 + div.width(); //div右边两个点的x的值
if (curX <= x1 || curX >= x2 || curY <= y1 || curY >= y2) {
} else {
_this.hideColumns(myTable);
_this.hideDropList(myTable);
_this.hideCondition(myTable);
}
});
} else {
types = {}; //存储过滤数据的类型
// 根据表格列显示
for (i = 0; i < columns.length; i++) {
if (columns[i].type === 'checkbox' || !columns[i].field) {
continue;
}
//存储过滤数据的类型
if (columns[i].filter && columns[i].filter.type) {
if (columns[i].filter.field) {
types[columns[i].filter.field] = columns[i].filter.type;
} else {
types[columns[i].field] = columns[i].filter.type;
}
}
}
if (JSON.stringify(types).length !== 2) {
myTable.where['tableFilterType'] = JSON.stringify(types);
}
}
// 初始化下拉数据
if ($('#soulDropList' + tableId).length === 0) {
$('body').append('<div id="soulDropList' + tableId + '" style="display: none"></div>');
}
if ($tableHead.find('.soul-table-filter').length > 0) {
var columnField = [], mainDataSwitch = filterItems.indexOf('data') !== -1;
$tableHead.find('.soul-table-filter').each(function (index, elem) {
if ($(this).data('column') && (mainDataSwitch ? (!$(this).data('items') || $(this).data('items').split(',').indexOf('data') !== -1) : $(this).data('items').split(',').indexOf('data') !== -1)) {
columnField.push($(this).data('column'));
}
});
if (columnField.length > 0) {
if (typeof myTable.url !== 'undefined' && myTable.page) {
var datas = JSON.parse(JSON.stringify(myTable.where)), url = myTable.url;
datas['columns'] = JSON.stringify(columnField);
$.ajax({
url: url,
data: datas,
dataType: 'json',
method: 'post',
headers: myTable.headers || {},
contentType: myTable.contentType,
success: function (result) {
var uls = [];
for (var key in result) {
var list = result[key];
if (!((list.length === 1 && list[0] === '') || list.length === 0)) {
var ul = [];
ul.push("<ul class='" + key + "DropList' data-value='" + key + "'>");
var columnsConfigs = columns;
for (j = 0; j < columnsConfigs.length; j++) {
if (columnsConfigs[j].field === key) {
if (columnsConfigs[j].filter.split) {
var tempList = []
for (i = 0; i < list.length; i++) {
var tempList2 = list[i].split(columnsConfigs[j].filter.split)
for (var k = 0; k < tempList2.length; k++) {
if (tempList.indexOf(tempList2[k]) === -1) {
tempList.push(tempList2[k]);
}
}
}
list = tempList;
}
list.sort(function (a, b) {
if (isNaN(a) || isNaN(b)) {
return String(a) >= String(b)
} else {
return Number(a) - Number(b)
}
})
for (i = 0; i < list.length; i++) {
if (UNHANDLED_VALUES.indexOf(list[i]) === -1) {
var line = {};
line[key] = list[i];
ul.push('<li data-value="' + String(list[i]).toLowerCase() + '"><input type="checkbox" value="' + list[i] + '" title="' + (_this.parseTempData(columnsConfigs[j], list[i], line, true)).replace(/\"|\'/g, '\'') + '" lay-skin="primary" lay-filter="soulDropList' + tableId + '"></li>')
}
}
break;
}
}
ul.push("</ul>");
uls.push(ul.join(''));
} else {
uls.push("<ul class='" + key + "DropList' data-value='" + key + "'><li style='color: gray;line-height: 25px;padding-left: 20px;'>(无数据)</li></ul>")
}
}
$('#soulDropList' + tableId).html(uls.join(''));
},
error: function () {
// layer.msg('列筛选数据查询失败!', {icon: 2, anim: 6})
}
})
} else {
var tableDatas = cache[myTable.id];
var dropDatas = {};
for (i = 0; i < tableDatas.length; i++) {
for (j = 0; j < columnField.length; j++) {
var value = typeof tableDatas[i][columnField[j]] === 'undefined' ? '' : tableDatas[i][columnField[j]];
if (dropDatas[columnField[j]]) {
if (dropDatas[columnField[j]].indexOf(value) === -1) {
dropDatas[columnField[j]].push(value);
}
} else {
dropDatas[columnField[j]] = [value]
}
}
}
var columnsConfigs = columns;
var uls = [];
for (j = 0; j < columnsConfigs.length; j++) {
var key = columnsConfigs[j].field;
var list = dropDatas[key];
if (list && !(list.length === 1 && list[0] === '')) {
if (columnsConfigs[j].filter && columnsConfigs[j].filter.split) {
var tempList = []
for (i = 0; i < list.length; i++) {
var tempList2 = String(list[i]).split(columnsConfigs[j].filter.split);
for (var k = 0; k < tempList2.length; k++) {
if (tempList.indexOf(tempList2[k]) === -1) {
tempList.push(tempList2[k])
}
}
}
list = tempList;
}
list.sort(function (a, b) {
if (isNaN(a) || isNaN(b)) {
return String(a) >= String(b)
} else {
return Number(a) - Number(b)
}
})
var ul = [];
ul.push("<ul class='" + key + "DropList' data-value='" + key + "'>");
for (i = 0; i < list.length; i++) {
if (UNHANDLED_VALUES.indexOf(list[i]) === -1) {
var line = {};
line[key] = list[i];
ul.push('<li data-value="' + String(list[i]).toLowerCase() + '"><input type="checkbox" value="' + list[i] + '" title="' + (_this.parseTempData(columnsConfigs[j], list[i], line, true)).replace(/\"|\'/g, '\'') + '" lay-skin="primary" lay-filter="soulDropList' + tableId + '"></li>')
}
}
ul.push("</ul>");
uls.push(ul.join(''));
} else {
uls.push("<ul class='" + key + "DropList' data-value='" + key + "'><li style='color: gray;line-height: 25px;padding-left: 20px;'>(无数据)</li></ul>")
}
}
$('#soulDropList' + tableId).html(uls.join(''));
}
} else {
_this.bindFilterClick(myTable);
}
}
this.bindFilterClick(myTable);
},
showConditionBoard: function (myTable) {
var _this = this,
tableId = myTable.id,
where = where_cache[myTable.id] || {},
tableFilterTypes = where.tableFilterType ? JSON.parse(where.tableFilterType) : {},
filterSos = where.filterSos ? JSON.parse(where.filterSos) : [],
filterBoard = [], fieldMap = {}, firstColumn, curItems,
filterItems = myTable.filter ? myTable.filter.items || defaultFilterItems : defaultFilterItems,
columns = _this.getCompleteCols(myTable.cols),
i;
for (i = 0; i < columns.length; i++) {
if (columns[i].field && columns[i].filter) {
if (!firstColumn) {
firstColumn = columns[i]
}
curItems = columns[i].filter.items || filterItems;
fieldMap[columns[i]['field']] = {
title: columns[i].title,
items: curItems
}
}
}
filterBoard.push('<div class="soul-edit-out">')
filterBoard.push('<div class="layui-form" lay-filter="soul-edit-out">')
filterBoard.push('<div><a class="layui-btn layui-btn-sm" data-type="addOne"><i class="layui-icon layui-icon-add-1"></i> 添加条件</a><a class="layui-btn layui-btn-sm" data-type="addGroup"><i class="layui-icon layui-icon-add-circle" ></i> 添加分组</a><a class="layui-btn layui-btn-sm" data-type="search" style="float: right"><i class="layui-icon layui-icon-search"></i> 查询</a><span style="float: right"><input type="checkbox" lay-filter="out_auto" class="out_auto" title="实时更新"></span></div>')
filterBoard.push('<hr>')
filterBoard.push('<ul>')
for (i = 0; i < filterSos.length; i++) {
groupHtml(filterSos[i], filterBoard, fieldMap, i === 0, i === (filterSos.length - 1))
}
filterBoard.push('</ul>')
filterBoard.push('</div>')
filterBoard.push('</div>')
layer.open({
title: '编辑条件',
type: 1,
offset: 'auto',
area: ['480px', '480px'],
content: filterBoard.join('')
})
form.render(null, 'soul-edit-out');
form.on('checkbox(out_auto)', function (data) {
if (data.elem.checked) {
_this.soulReload(myTable);
}
})
function groupHtml(filterSo, filterBoard, fieldMap, isFirst, isLast) {
var id = filterSo.id,
field = filterSo.field,
mode = filterSo.mode,
type = filterSo.type,
isOr = filterSo.prefix === 'or';
filterBoard.push('<li data-id="' + id + '" data-field="' + field + '" ' + (isLast ? 'class="last"' : '') + ' data-mode="' + mode + '" data-type="' + type + '" data-value="' + (typeof filterSo.value === 'undefined' ? '' : filterSo.value) + '" >');
filterBoard.push('<div><table><tbody><tr><td data-type="top"></td></tr><tr><td data-type="bottom"></td></tr></tbody></table></div>')
// if (!isFirst) { //第一个隐藏 与或
filterBoard.push('<div><input type="checkbox" name="switch" lay-filter="soul-edit-switch" lay-skin="switch" lay-text="与|或" ' + (isOr ? '' : 'checked') + '></div>')
// }
switch (mode) {
case 'in':
filterBoard.push('<div class="layui-firebrick item-field">' + (fieldMap[field].title) + '</div>');
filterBoard.push('<div class="layui-deeppink item-type" >筛选数据</div>');
filterBoard.push('<div class="layui-blueviolet item-value">共' + (filterSo.values ? filterSo.values.length : 0) + '条数据</div>');
filterBoard.push('<div class="layui-red delete-item"><i class="layui-icon layui-icon-close-fill"></i></div>');
break;
case 'date':
filterBoard.push('<div class="layui-firebrick item-field">' + (fieldMap[field].title) + '</div>');
filterBoard.push('<div class="layui-deeppink item-type">选择日期</div>');
filterBoard.push('<div class="layui-blueviolet item-value">' + (filterSo.type === 'specific' ? filterSo.value || '请选择' : dateTimeItems[filterSo.type]) + '</div>');
filterBoard.push('<div class="layui-red delete-item"><i class="layui-icon layui-icon-close-fill"></i></div>');
break;
case 'condition':
filterBoard.push('<div class="layui-firebrick item-field">' + (fieldMap[field].title) + '</div>');
filterBoard.push('<div class="layui-deeppink item-type">' + conditionChangeItems[filterSo.type] + '</div>');
if (type !== 'null' && type !== 'notNull') {
filterBoard.push('<div class="layui-blueviolet item-value">' + (typeof filterSo.value === 'undefined' || filterSo.value === '' ? '请输入...' : filterSo.value) + '</div>');
}
filterBoard.push('<div class="layui-red delete-item"><i class="layui-icon layui-icon-close-fill"></i></div>');
break;
case 'group':
filterBoard.push('<div class="layui-firebrick">分组</div>')
filterBoard.push('<div><a class="layui-btn layui-btn-xs" data-type="addOne"><i class="layui-icon layui-icon-add-1"></i> 添加条件</a><a class="layui-btn layui-btn-xs" data-type="addGroup"><i class="layui-icon layui-icon-add-circle"></i> 添加分组</a></div>')
filterBoard.push('<div class="layui-red delete-item"><i class="layui-icon layui-icon-close-fill"></i></div>');
filterBoard.push('<ul class="group ' + (isLast ? '' : 'line') + '">');
if (filterSo.children) {
for (var i = 0; i < filterSo.children.length; i++) {
groupHtml(filterSo.children[i], filterBoard, fieldMap, i === 0, i === (filterSo.children.length - 1));
}
}
filterBoard.push('</ul>');
break;
}
filterBoard.push('</li>')
}
// prefix
form.on('switch(soul-edit-switch)', function (data) {
changePrefix(data)
})
// column
$('.soul-edit-out .item-field').on('click', function (e) {
e.stopPropagation();
showColums(this)
})
// type
$('.soul-edit-out .item-type').on('click', function (e) {
e.stopPropagation();
showTypes(this)
})
// value
$('.soul-edit-out .item-value').on('click', function (e) {
e.stopPropagation();
showValue(this)
})
// delete
$('.soul-edit-out .delete-item').on('click', function () {
var id = $(this).parent().data('id'),
refresh = $('.soul-edit-out .out_auto').prop('checked');
$(this).parent().remove();
_this.updateWhere(myTable, {
id: id,
delete: true
})
if (refresh) {
_this.soulReload(myTable);
}
})
function changePrefix(data) {
var prefix = data.elem.checked ? 'and' : 'or',
id = $(data.elem).parents('li:eq(0)').data('id'),
refresh = $('.soul-edit-out .out_auto').prop('checked');
$(data.elem).parents('li:eq(0)').data('prefix', prefix);
_this.updateWhere(myTable, {
id: id,
prefix: prefix
})
if (refresh) {
_this.soulReload(myTable)
}
}
function showColums(obj) {
_this.hideDropList(myTable);
_this.hideCondition(myTable);
_this.hideColumns(myTable);
_this.hideBfPrefix(myTable)
_this.hideBfType(myTable);
var top = $(obj).offset().top + $(obj).outerHeight(),
left = $(obj).offset().left;
$('#soul-bf-column' + tableId).find('li.soul-bf-selected').removeClass('soul-bf-selected')
$('#soul-bf-column' + tableId)
.data('field', $(obj).parent().data('field'))
.data('id', $(obj).parent().data('id'))
.data('mode', $(obj).parent().data('mode'))
.data('group', $(obj).parents('li:eq(2)').data('id') || '')
.data('refresh', $('.soul-edit-out .out_auto').prop('checked'))
.show()
.css({top: top, left: left})
.removeClass().addClass('fadeInUp animated')
.find('li[data-field="' + $(obj).parent().data('field') + '"]')
.addClass('soul-bf-selected')
}
function showTypes(obj) {
_this.hideDropList(myTable);
_this.hideCondition(myTable);
_this.hideColumns(myTable);
_this.hideBfColumn(myTable);
_this.hideBfPrefix(myTable);
var top = $(obj).offset().top + $(obj).outerHeight(),
left = $(obj).offset().left,
field = $(obj).parent().data('field');
$('#soul-bf-type' + tableId + ' li').hide()
if (tableFilterTypes[field] && tableFilterTypes[field].indexOf('date') === 0) {
$('#soul-bf-type' + tableId + ' li[data-mode=date]').show()
}
if (fieldMap[field].items.indexOf('data') !== -1) {
$('#soul-bf-type' + tableId + ' li[data-mode=in]').show()
}
if (fieldMap[field].items.indexOf('condition') !== -1) {
$('#soul-bf-type' + tableId + ' li[data-mode=condition]').show()
}
$('#soul-bf-type' + tableId).find('li.soul-bf-selected').removeClass('soul-bf-selected')
switch ($(obj).parent().data('mode')) {
case 'in':
$('#soul-bf-type' + tableId).find('li[data-mode="in"]')
.addClass('soul-bf-selected')
break;
case 'date':
$('#soul-bf-type' + tableId).find('li[data-mode="date"]')
.addClass('soul-bf-selected')
case 'condition':
$('#soul-bf-type' + tableId).find('li[data-value="' + $(obj).parent().data('type') + '"]')
.addClass('soul-bf-selected')
}
$('#soul-bf-type' + tableId)
.data('type', $(obj).parent().data('type'))
.data('mode', $(obj).parent().data('mode'))
.data('id', $(obj).parent().data('id'))
.data('group', $(obj).parents('li:eq(2)').data('id') || '')
.data('refresh', $('.soul-edit-out .out_auto').prop('checked'))
.show()
.css({top: top, left: left})
.removeClass().addClass('fadeInUp animated')
}
function showValue(obj) {
_this.hideColumns(myTable);
_this.hideBfType(myTable);
_this.hideBfPrefix(myTable)
_this.hideBfColumn(myTable);
var top,
left = $(obj).offset().left,
mode = $(obj).parent().data('mode'),
field = $(obj).parent().data('field'),
id = $(obj).parent().data('id'),
head = $(obj).parent().data('head'),
prefix = $(obj).parent().data('prefix'),
value = $(obj).parent().data('value'),
refresh = $('.soul-edit-out .out_auto').prop('checked'),
where = where_cache[myTable.id] || {},
filterSos = where.filterSos ? JSON.parse(where.filterSos) : [];
switch (mode) {
case 'in':
_this.hideCondition(myTable);
if (dorpListTimeOut) {
clearTimeout(dorpListTimeOut);
}
$('#soul-dropList' + tableId + '>.filter-search>input').val('');
$('#soul-dropList' + tableId).show();
$('#soulDropList' + tableId).find('.' + field + 'DropList li input[type=checkbox]:checked').prop('checked', false);
var filterSo = _this.getFilterSoById(filterSos, id);
if (filterSo.values) {
for (i = 0; i < filterSo.values.length; i++) {
$('#soulDropList' + tableId).find('.' + field + 'DropList li input[type=checkbox][value="' + filterSo.values[i] + '"]').prop('checked', true);
}
}
$('#soul-dropList' + tableId + '>ul').data('id', id).data('head', head).data('refresh', refresh).data('prefix', prefix).html($('#soulDropList' + tableId).find('.' + field + 'DropList li').clone());
form.render('checkbox', 'orm');
top = $(obj).offset().top + $(obj).outerHeight();
$('#soul-dropList' + tableId).css({'top': top, 'left': left})
.show().removeClass().addClass('fadeInUp animated');
setTimeout(function () {
$('#soul-dropList' + tableId + '>.filter-search>input').focus() // 聚焦搜索框
}, 1);
// 监听筛选数据
var liClick = true;
form.on('checkbox(soulDropList' + tableId + ')', function (data) {
liClick = false;
_this.updateDropList(myTable, field);
});
$('#soul-dropList' + tableId + '>ul>li[data-value]').on('click', function () {
if (liClick) {
$(this).find('div.layui-form-checkbox').trigger('click');
}
liClick = true;
})
break;
case 'date':
_this.hideDropList(myTable);
if (conditionTimeOut) {
clearTimeout(conditionTimeOut);
}
var filterSo = _this.getFilterSoById(filterSos, id),
top = $(obj).offset().top + $(obj).height();
_this.showDate(myTable, field, filterSo, "fadeInUp", top, left, "down", refresh);
break;
case 'condition':
$(obj).hide();
$(obj).after('<div><input class="layui-input tempValue" value="" /></div>')
$(obj).next().children().val(value).select().on('keydown', function (e) {
if (e.keyCode === 13) {
$(this).blur();
}
}).on('blur', function () {
var newValue = $(this).val();
$(obj).html(typeof newValue === 'undefined' || newValue === '' ? '请输入...' : newValue);
$(obj).show();
$(this).parent().remove()
if (newValue !== value) {
$(obj).parent().data('value', newValue);
_this.updateWhere(myTable, {
id: id,
value: newValue
})
if (refresh) {
_this.soulReload(myTable);
}
}
})
break;
}
}
$('.soul-edit-out a[data-type]').on('click', function () {
if ($(this).data('type') === 'search') {
_this.soulReload(myTable);
} else {
addLine(this)
}
})
function addLine(obj) {
var refresh = $('.soul-edit-out .out_auto').prop('checked');
filterBoard = []
switch ($(obj).data('type')) {
case 'addOne':
var filterSo = {
prefix: 'and',
field: firstColumn.field,
mode: 'condition',
type: 'eq',
value: ''
}
if ($(obj).parent().parent().data('id')) {
$.extend(filterSo, {
groupId: $(obj).parent().parent().data('id')
})
}
_this.updateWhere(myTable, filterSo);
filterBoard.push('<li data-id="' + filterSo.id + '" data-field="' + filterSo.field + '" data-mode="' + filterSo.mode + '" data-type="' + filterSo.type + '" data-value="' + filterSo.value + '" data-prefix="' + filterSo.prefix + '" class="last">');
filterBoard.push('<div><table><tbody><tr><td data-type="top"></td></tr><tr><td data-type="bottom"></td></tr></tbody></table></div>');
filterBoard.push('<div><input type="checkbox" name="switch" lay-filter="soul-edit-switch" lay-skin="switch" lay-text="与|或" checked></div>')
filterBoard.push('<div class="layui-firebrick item-field">' + fieldMap[filterSo.field].title + '</div>');
filterBoard.push('<div class="layui-deeppink item-type">等于</div>');
filterBoard.push('<div class="layui-blueviolet item-value">请输入...</div>');
filterBoard.push('<div class="layui-red delete-item"><i class="layui-icon layui-icon-close-fill"></i></div>');
filterBoard.push('</li>');
break;
case 'addGroup':
var filterSo = {
prefix: 'and',
mode: 'group',
children: []
}
if ($(obj).parent().parent().data('id')) {
$.extend(filterSo, {
groupId: $(obj).parent().parent().data('id')
})
}
_this.updateWhere(myTable, filterSo);
filterBoard.push('<li data-id="' + filterSo.id + '" class="last">');
filterBoard.push('<div><table><tbody><tr><td data-type="top"></td></tr><tr><td data-type="bottom"></td></tr></tbody></table></div>');
filterBoard.push('<div><input type="checkbox" name="switch" lay-filter="soul-edit-switch" lay-skin="switch" lay-text="与|或" checked></div>')
filterBoard.push('<div class="layui-firebrick">分组</div>')
filterBoard.push('<div><a class="layui-btn layui-btn-xs" data-type="addOne"><i class="layui-icon layui-icon-add-1"></i> 添加条件</a><a class="layui-btn layui-btn-xs" data-type="addGroup"><i class="layui-icon layui-icon-add-circle"></i> 添加分组</a></div>')
filterBoard.push('<div class="layui-red delete-item"><i class="layui-icon layui-icon-close-fill"></i></div>');
filterBoard.push('<ul class="group">');
filterBoard.push('</ul>');
filterBoard.push('</li>');
break;
}
if (refresh) {
_this.soulReload(myTable);
}
if ($(obj).parent().parent().children('ul').children('li').length > 0) {
$(obj).parent().parent().children('ul').children('li:last').removeClass('last');
if ($(obj).parent().parent().children('ul').children('li:last').children('ul.group').length > 0) {
$(obj).parent().parent().children('ul').children('li:last').children('ul.group').addClass('line')
}
}
$(obj).parent().parent().children('ul').append(filterBoard.join(''));
form.render('checkbox', 'soul-edit-out')
if ($(obj).data('type') === 'addGroup') {
$(obj).parent().parent().children('ul').children("li:last").find('a[data-type]').on('click', function () {
addLine(this)
})
} else {
$(obj).parent().parent().children('ul').children("li:last").find('.item-field').on('click', function (e) {
e.stopPropagation();
showColums(this);
})
$(obj).parent().parent().children('ul').children("li:last").find('.item-type').on('click', function (e) {
e.stopPropagation();
showTypes(this);
})
$(obj).parent().parent().children('ul').children("li:last").find('.item-value').on('click', function (e) {
e.stopPropagation();
showValue(this);
})
}
$(obj).parent().parent().children('ul').children("li:last").children('.delete-item').on('click', function () {
var id = $(this).parent().data('id'),
refresh = $('.soul-edit-out .out_auto').prop('checked');
$(this).parent().remove();
_this.updateWhere(myTable, {
id: id,
delete: true
})
if (refresh) {
_this.soulReload(myTable);
}
})
}
}
, hideColumns: function (myTable, animate) {
var tableId = myTable.id;
$('#soul-columns' + tableId).removeClass().addClass('fadeOutLeft animated')
if (columnsTimeOut) {
clearTimeout(columnsTimeOut)
}
if (typeof animate === 'undefined' || animate) {
columnsTimeOut = setTimeout(function (e) {
$('#soul-columns' + tableId).hide();
}, 500)
} else {
$('[id^=soul-columns]').hide();
}
}
, hideDropList: function (myTable, animate) {
var tableId = myTable.id;
$('#soul-dropList' + tableId).removeClass().addClass('fadeOutLeft animated')
if (dorpListTimeOut) {
clearTimeout(dorpListTimeOut);
}
if (typeof animate === 'undefined' || animate) {
dorpListTimeOut = setTimeout(function (e) {
$('#soul-dropList' + tableId).hide();
}, 500)
} else {
$('[id^=soul-dropList]').hide();
}
}
, hideCondition: function (myTable, animate) {
var tableId = myTable.id;
$('#soul-condition' + tableId).removeClass().addClass('fadeOutLeft animated')
if (conditionTimeOut) {
clearTimeout(conditionTimeOut);
}
if (typeof animate === 'undefined' || animate) {
conditionTimeOut = setTimeout(function (e) {
$('#soul-condition' + tableId).hide();
}, 500)
} else {
$('[id^=soul-condition]').hide();
}
}
, hideBfPrefix: function (myTable, animate) {
var tableId = myTable.id;
$('#soul-bf-prefix' + tableId).removeClass().addClass('fadeOutDown animated')
if (bfColumnTimeOut) {
clearTimeout(bfColumnTimeOut);
}
if (typeof animate === 'undefined' || animate) {
bfColumnTimeOut = setTimeout(function () {
$('#soul-bf-prefix' + tableId).hide();
}, 500)
} else {
$('[id=soul-bf-prefix' + tableId + ']').hide();
}
}
, hideBfColumn: function (myTable, animate) {
var tableId = myTable.id;
$('#soul-bf-column' + tableId).removeClass().addClass('fadeOutDown animated')
if (bfColumnTimeOut) {
clearTimeout(bfColumnTimeOut);
}
if (typeof animate === 'undefined' || animate) {
bfColumnTimeOut = setTimeout(function () {
$('#soul-bf-column' + tableId).hide();
}, 500)
} else {
$('[id=soul-bf-column' + tableId + ']').hide();
}
}
, hideBfType: function (myTable, animate) {
var tableId = myTable.id;
$('#soul-bf-type' + tableId).removeClass().addClass('fadeOutDown animated')
if (bfCond1TimeOut) {
clearTimeout(bfCond1TimeOut);
}
if (typeof animate === 'undefined' || animate) {
bfCond1TimeOut = setTimeout(function () {
$('#soul-bf-type' + tableId).hide();
}, 500)
} else {
$('[id=soul-bf-type' + tableId + ']').hide();
}
}
, bindFilterClick: function (myTable) {
var _this = this,
$table = $(myTable.elem),
$tableHead = $table.next().children('.layui-table-box').children('.layui-table-header').children('table'),
$fixedLeftTableHead = $table.next().children('.layui-table-box').children('.layui-table-fixed-l').children('.layui-table-header').children('table'),
$fixedRigthTableHead = $table.next().children('.layui-table-box').children('.layui-table-fixed-r').children('.layui-table-header').children('table'),
tableId = myTable.id,
filterItems = myTable.filter ? myTable.filter.items || defaultFilterItems : defaultFilterItems,
mainListTimeOut;
// 显示筛选框
$tableHead.find('.soul-table-filter').off('click').on('click', function (e) {
e.stopPropagation();
showFilter($(this))
});
$fixedLeftTableHead.find('.soul-table-filter').off('click').on('click', function (e) {
e.stopPropagation();
showFilter($(this))
});
$fixedRigthTableHead.find('.soul-table-filter').off('click').on('click', function (e) {
e.stopPropagation();
showFilter($(this))
});
function showFilter($that) {
var curItems = $that.data('items') ? $that.data('items').split(',') : filterItems
_this.hideColumns(myTable, false);
_this.hideDropList(myTable, false);
_this.hideCondition(myTable, false);
$('[id^=main-list]').hide();
$('#main-list' + tableId).data({'field': $that.data('column'), 'split': $that.data('split')});
$('#soul-columns' + tableId + ' [type=checkbox]').attr('disabled', false);
// if (myTable.cols[0][0].type=='checkbox') {
// $('#soul-columns'+tableId+' [type=checkbox]:eq('+($that.parents('th').data('key').split('-')[2]-1)+')').attr('disabled', true);
// } else {
$('#soul-columns' + tableId + ' li[data-key=' + $that.parents('th').data('key').split('-')[2] + '] [type=checkbox]').attr('disabled', true);
// }
$('#main-list' + tableId + ' > li').hide()
// 是否显示排序框
if ($that.hasClass('layui-table-sort')) {
$('#main-list' + tableId + ' .soul-sort').show()
}
for (var i = 0; i < curItems.length; i++) {
$('#main-list' + tableId + ' .' + itemsMap[curItems[i]]).show()
if ($('#main-list' + tableId + ' .' + itemsMap[curItems[i]]).index() !== (i + 2)) {
$('#main-list' + tableId + '>li:eq("' + (i + 2) + '")').before($('#main-list' + tableId + ' .' + itemsMap[curItems[i]]))
}
}
if (mainListTimeOut) {
clearTimeout(mainListTimeOut)
}
var left, animate;
if ($that.offset().left + $('#main-list' + tableId).outerWidth() < document.body.clientWidth) {
left = $that.offset().left + 10;
animate = 'fadeInLeft';
} else {
left = $that.offset().left - $('#main-list' + tableId).outerWidth();
animate = 'fadeInRight';
}
$('#main-list' + tableId).data('type', myTable.where.tableFilterType ? JSON.parse(myTable.where.tableFilterType)[$that.data('column')] || '' : '').hide().css({
'top': $that.offset().top + 10,
'left': left
}).show().removeClass().addClass(animate + ' animated');
// 排序
$('#main-list' + tableId + ' .soul-sort').on('click', function (e) {
$that.siblings('.layui-table-sort').find('.layui-table-sort-' + $(this).data('value')).trigger('click');
$('#main-list' + tableId).hide();
})
form.render('checkbox', 'orm');
}
$(document).on('click', function (e) {
$('#main-list' + tableId).hide();
_this.hideColumns(myTable, false);
_this.hideDropList(myTable, false);
_this.hideCondition(myTable, false);
_this.hideBfPrefix(myTable, false);
_this.hideBfColumn(myTable, false);
_this.hideBfType(myTable, false);
});
$('#main-list' + tableId + ',#soul-columns' + tableId + ',#soul-dropList' + tableId + ',#soul-condition' + tableId).on('click', function (e) {
$(this).find('.layui-form-selected').removeClass('layui-form-selected')
e.stopPropagation();
});
//渲染底部筛选条件
_this.renderBottomCondition(myTable);
// 表头样式
var where = where_cache[myTable.id] || {},
filterSos = JSON.parse(where.filterSos ? where.filterSos : '[]');
for (var i = 0; i < filterSos.length; i++) {
if (filterSos[i].head) {
var hasFilter = false;
switch (filterSos[i].mode) {
case 'in':
if (filterSos[i].values && filterSos[i].values.length > 0) {
hasFilter = true
}
break;
case 'date':
if (filterSos[i].type !== 'all' && typeof filterSos[i].value !== 'undefined' && filterSos[i].value !== '') {
hasFilter = true
}
break;
case 'group':
if (filterSos[i].children && filterSos[i].children.length > 0) {
hasFilter = true
}
default:
break;
}
$tableHead.find('thead>tr>th[data-field="' + filterSos[i].field + '"] .soul-table-filter').attr('soul-filter', '' + hasFilter);
$fixedLeftTableHead.find('thead>tr>th[data-field="' + filterSos[i].field + '"] .soul-table-filter').attr('soul-filter', '' + hasFilter);
$fixedRigthTableHead.find('thead>tr>th[data-field="' + filterSos[i].field + '"] .soul-table-filter').attr('soul-filter', '' + hasFilter);
}
}
}
, resize: function (myTable) {
var _this = this,
$table = $(myTable.elem),
$tableBox = $table.next().children('.layui-table-box'),
$tableMain = $tableBox.children('.layui-table-main')
// 减去底部筛选的高度
if ($table.next().children('.soul-bottom-contion').length > 0) {
$table.next().children('.soul-bottom-contion').children('.condition-items').css('width', $table.next().children('.soul-bottom-contion').width() - $table.next().children('.soul-bottom-contion').children('.editCondtion').outerWidth());
var bodyHeight = $table.next().height() - $table.next().children('.soul-bottom-contion').outerHeight()
if ($table.next().children('.layui-table-tool').length > 0) {
bodyHeight = bodyHeight - $table.next().children('.layui-table-tool').outerHeight();
}
if ($table.next().children('.layui-table-total').length > 0) {
bodyHeight = bodyHeight - $table.next().children('.layui-table-total').outerHeight();
}
if ($table.next().children('.layui-table-page').length > 0) {
bodyHeight = bodyHeight - $table.next().children('.layui-table-page').outerHeight();
}
bodyHeight = bodyHeight - $table.next().children('.layui-table-box').children('.layui-table-header').outerHeight();
$table.next().children('.layui-table-box').children('.layui-table-body').height(bodyHeight)
var fixHeight = bodyHeight - _this.getScrollWidth($tableMain[0]),
layMainTableHeight = $tableMain.children('table').height()
$table.next().children('.layui-table-box').children('.layui-table-fixed').children('.layui-table-body').height(layMainTableHeight >= fixHeight ? fixHeight : 'auto')
var scollWidth = $tableMain.width() - $tableMain.prop('clientWidth') //纵向滚动条宽度;
$tableBox.children('.layui-table-fixed-r').css('right', scollWidth - 1);
}
}
/**
* 同步当前 droplist
* @param myTable
* @param field
*/
, updateDropList: function (myTable, field) {
var _this = this,
$table = $(myTable.elem),
tableId = myTable.id,
id = $('#soul-dropList' + tableId + '>ul').data('id'),
$checkedDom = $('#soul-dropList' + tableId + '>ul input[type=checkbox]:checked'),
values = [],
head = $('#soul-dropList' + tableId + '>ul').data('head'),
prefix = $('#soul-dropList' + tableId + '>ul').data('prefix'),
refresh = $('#soul-dropList' + tableId + '>ul').data('refresh'),
split = $('#soul-dropList' + tableId + '>ul').data('split');
if ($checkedDom.length > 0) {
$checkedDom.each(function () {
values.push($(this).val())
})
}
var filterSo = {
id: id,
head: head,
prefix: prefix || 'and',
mode: 'in',
field: field,
split: split,
values: values
};
_this.updateWhere(myTable, filterSo);
if (!id) {
$('#soul-dropList' + tableId + '>ul').data('id', filterSo.id);
}
if ($('.soul-edit-out').length > 0) {
$('.soul-edit-out li[data-id="' + filterSo.id + '"]>.item-value').html('' + (filterSo.values ? filterSo.values.length : 0) + '条数据')
}
if (refresh) {
_this.soulReload(myTable);
}
}
, getFilterSoById: function (filterSos, id) {
for (var i = 0; i < filterSos.length; i++) {
if (filterSos[i].id === id) {
return filterSos[i]
} else if (filterSos[i].mode === 'group') {
for (var j = 0; j < filterSos[i].children.length; j++) {
var filterSo = this.getFilterSoById(filterSos[i].children, id);
if (filterSo) return filterSo;
}
}
}
return null
}
/**
* 更新 filter 条件
* @param myTable
* @param filterSo
*/
, updateWhere: function (myTable, filterSo) {
var _this = this,
where = where_cache[myTable.id] || {},
filterSos = JSON.parse(where.filterSos ? where.filterSos : '[]');
if (filterSo.id || filterSo.groupId) {
for (var i = 0; i < filterSos.length; i++) {
if (filterSo.delete && filterSos[i].id === filterSo.id) {
filterSos.splice(i, 1);
break;
}
if (updateFilterSo(filterSos[i], filterSo)) {
break;
}
}
} else if (!(filterSo.mode === 'in' && !(filterSo.values && filterSo.values.length > 0))) {
filterSos.push($.extend(filterSo, {
id: _this.getDifId()
}))
}
where['filterSos'] = JSON.stringify(filterSos);
myTable.where = where;
where_cache[myTable.id] = where;
function updateFilterSo(filterSo, newFilterSo) {
var isMatch = false;
if (filterSo.id === newFilterSo.id) {
$.extend(filterSo, newFilterSo);
isMatch = true;
}
// 在分组中新增
if (!newFilterSo.id && filterSo.id === newFilterSo.groupId) {
filterSo.children.push($.extend(newFilterSo, {
id: _this.getDifId()
}))
} else if (filterSo.mode === 'group') {
for (var i = 0; i < filterSo.children.length; i++) {
if (newFilterSo.delete && filterSo.children[i].id === newFilterSo.id) {
filterSo.children.splice(i, 1);
return true;
}
if (updateFilterSo(filterSo.children[i], newFilterSo)) {
return true;
}
}
}
return isMatch;
}
}
/**
* 根据当前条件重载表格
* @param myTable 需要重载的表格对象
* @param isr 是否为筛选重载,为 true 时,不进行筛选的初始化动作(包括渲染dom、请求表头数据等)
*/
, soulReload: function (myTable, isr) {
var _this = this,
$table = $(myTable.elem),
scrollLeft = $table.next().children('.layui-table-box').children('.layui-table-main').scrollLeft();
isFilterReload[myTable.id] = typeof isr === 'undefined' ? true : isr;
if (typeof myTable.url !== 'undefined' && myTable.page) {
$table.data('scrollLeft', scrollLeft);
/**
* 后台筛选
*/
table.reload(myTable.id, {
where: where_cache[myTable.id] || {},
page: {
curr: 1 //重新从第 1 页开始
}
})
} else {
/**
* 前端筛选
*/
var where = where_cache[myTable.id] || {},
filterSos = JSON.parse(where.filterSos ? where.filterSos : '[]'),
tableFilterTypes = where.tableFilterType ? JSON.parse(where.tableFilterType) : {},
loading = layer.load(2);
if (!myTable.page) {
// 修复前端不分页时,layui table bug 导致的只显示10条数据的问题
myTable.limit = 100000000
}
if (filterSos.length > 0) {
var newData = [];
layui.each(cache[myTable.id], function (index, item) {
var show = true;
for (var i = 0; i < filterSos.length; i++) {
show = _this.handleFilterSo(filterSos[i], item, tableFilterTypes, show, i === 0)
}
if (show) {
newData.push(item)
}
})
if (myTable.page) {
table.reload(myTable.id, {
data: newData
, initSort: myTable.initSort
, isSoulFrontFilter: true
, page: {
curr: 1 //重新从第 1 页开始
}
})
} else {
var url = myTable.url;
$table.next().off('click')
var inst = table.reload(myTable.id, {
url: ''
, initSort: myTable.initSort
, isSoulFrontFilter: true
, data: newData
})
inst.config.url = url;
}
myTable.data = newData
} else {
if (myTable.page) {
table.reload(myTable.id, {
data: cache[myTable.id]
, initSort: myTable.initSort
, isSoulFrontFilter: true
, page: {
curr: 1 //重新从第 1 页开始
}
})
} else {
table.reload(myTable.id, {
data: cache[myTable.id]
, initSort: myTable.initSort
, isSoulFrontFilter: true
})
}
myTable.data = cache[myTable.id]
}
$table.next().children('.layui-table-box').children('.layui-table-main').scrollLeft(scrollLeft);
layer.close(loading)
}
}
, handleFilterSo: function (filterSo, item, tableFilterTypes, show, first) {
var isOr = first ? false : filterSo.prefix === 'or',
field = filterSo.field,
value = filterSo.value,
status = true;
// 如果有子元素
if (filterSo.children && filterSo.children.length > 0) {
for (var i = 0; i < filterSo.children.length; i++) {
status = this.handleFilterSo(filterSo.children[i], item, tableFilterTypes, status, i === 0)
}
return isOr ? show || status : show && status;
}
switch (filterSo.mode) {
case "in":
if (filterSo.values && filterSo.values.length > 0) {
if (filterSo.split) {
var tempList = (item[field] + '').split(filterSo.split);
var tempStatus = false;
for (var i = 0; i < tempList.length; i++) {
if (filterSo.values.indexOf(tempList[i]) !== -1) {
tempStatus = true;
}
}
status = tempStatus;
} else {
status = filterSo.values.indexOf(item[field] + '') !== -1
}
} else {
return show;
}
break;
case "condition":
if (filterSo.type !== 'null' && filterSo.type !== 'notNull' && (typeof value === 'undefined' || value === '')) {
return show;
}
switch (filterSo.type) {
case "eq":
status = isNaN(item[field]) || isNaN(value) ? item[field] === value : Number(item[field]) === Number(value);
break;
case "ne":
status = isNaN(item[field]) || isNaN(value) ? item[field] !== value : Number(item[field]) !== Number(value);
break;
case "gt":
status = isNaN(item[field]) || isNaN(value) ? item[field] > value : Number(item[field]) > Number(value);
break;
case "ge":
status = isNaN(item[field]) || isNaN(value) ? item[field] >= value : Number(item[field]) >= Number(value);
break;
case "lt":
status = isNaN(item[field]) || isNaN(value) ? item[field] < value : Number(item[field]) < Number(value);
break;
case "le":
status = isNaN(item[field]) || isNaN(value) ? item[field] <= value : Number(item[field]) <= Number(value);
break;
case "contain":
status = (item[field] + '').indexOf(value) !== -1;
break;
case "notContain":
status = (item[field] + '').indexOf(value) === -1;
break;
case "start":
status = (item[field] + '').indexOf(value) === 0;
break;
case "end":
var d = (item[field] + '').length - (value + '').length;
status = d >= 0 && (item[field] + '').lastIndexOf(value) === d;
break;
case "null":
status = typeof item[field] === 'undefined' || item[field] === '' || item[field] === null;
break;
case "notNull":
status = typeof item[field] !== 'undefined' && item[field] !== '' && item[field] !== null;
break;
}
break;
case "date":
var dateVal = new Date(Date.parse(item[field].replace(/-/g, "/")));
switch (filterSo.type) {
case 'all':
status = true;
break;
case 'yesterday':
status = item[field] && isBetween(dateVal, getToday() - 86400, getToday() - 1);
break;
case 'thisWeek':
status = item[field] && isBetween(dateVal, getFirstDayOfWeek(), getFirstDayOfWeek() + 86400 * 7 - 1);
break;
case 'lastWeek':
status = item[field] && isBetween(dateVal, getFirstDayOfWeek() - 86400 * 7, getFirstDayOfWeek() - 1);
break;
case 'thisMonth':
status = item[field] && isBetween(dateVal, getFirstDayOfMonth(), getCurrentMonthLast());
break;
case 'thisYear':
status = item[field] && isBetween(dateVal, new Date(new Date().getFullYear(), 1, 1) / 1000, new Date(new Date().getFullYear() + 1, 1, 1) / 1000 - 1);
break;
case 'specific':
var dateFormat = dateVal.getFullYear();
dateFormat += '-' + (timeAdd0(dateVal.getMonth() + 1));
dateFormat += '-' + timeAdd0(dateVal.getDate());
status = item[field] && dateFormat === value
break;
}
break;
}
// 今天凌晨
function getToday() {
return new Date().setHours(0, 0, 0, 0) / 1000;
}
// 本周第一天
function getFirstDayOfWeek() {
var now = new Date();
var weekday = now.getDay() || 7; //获取星期几,getDay()返回值是 0(周日) 到 6(周六) 之间的一个整数。0||7为7,即weekday的值为1-7
return new Date(now.setDate(now.getDate() - weekday + 1)).setHours(0, 0, 0, 0) / 1000;//往前算(weekday-1)天,年份、月份会自动变化
}
//获取当月第一天
function getFirstDayOfMonth() {
return new Date(new Date().setDate(1)).setHours(0, 0, 0, 0) / 1000;
}
//获取当月最后一天最后一秒
function getCurrentMonthLast() {
var date = new Date();
var currentMonth = date.getMonth();
var nextMonth = ++currentMonth;
var nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
return nextMonthFirstDay / 1000 - 1;
}
function isBetween(v, a, b) {
return (v.getTime() / 1000) >= a && (v.getTime() / 1000) <= b;
}
function timeAdd0(str) {
str += "";
if (str.length <= 1) {
str = '0' + str;
}
return str
}
return isOr ? show || status : show && status;
}
, getDifId: function () {
return maxId++;
}
, showDate: function (myTable, field, filterSo, animate, top, left, type, refresh) {
var _this = this,
tableId = myTable.id,
conditionHtml = [],
documentWidth = document.body.clientWidth,
animate;
conditionHtml.push('<div class="' + field + 'Condition" data-value="' + field + '" style="padding: 5px;" >');
conditionHtml.push('<div class="layui-row">');
for (var key in dateTimeItems) {
conditionHtml.push('<div class="layui-col-sm4"><input type="radio" name="datetime' + tableId + field + '" lay-filter="datetime' + tableId + '" value="' + key + '" title="' + dateTimeItems[key] + '"></div>');
}
conditionHtml.push('</div>');
conditionHtml.push('<div><input type="radio" name="datetime' + tableId + field + '" lay-filter="datetime' + tableId + '" value="specific" title="过滤具体日期"> <input type="hidden" class="specific_value"><div class="staticDate"></div></div></div>');
$('#soul-condition' + tableId).html(conditionHtml.join(''));
var filterDate = util.toDateString(new Date(), 'yyyy-MM-dd');
if (filterSo) {
$('#soul-condition' + tableId).data({'id': filterSo.id, 'head': true});
$('#soul-condition' + tableId + '>.' + field + 'Condition' + ' [name^=datetime][value="' + filterSo.type + '"]').prop('checked', true);
if (filterSo.type === 'specific') {
filterDate = filterSo.value
}
} else {
$('#soul-condition' + tableId).data({'id': '', 'head': true});
$('#soul-condition' + tableId + '>.' + field + 'Condition' + ' [name^=datetime][value="all"]').prop('checked', true);
}
$('#soul-condition' + tableId + ' .specific_value').val(filterDate);
laydate.render({
elem: '#soul-condition' + tableId + ' .staticDate'
, position: 'static'
, calendar: true
, btns: ['now']
, value: filterDate
, done: function (value) {
var id = $('#soul-condition' + tableId).data('id'),
head = $('#soul-condition' + tableId).data('head')
$('#soul-condition' + tableId + ' .specific_value').val(value);
$('#soul-condition' + tableId + ' [name^=datetime]:checked').prop('checked', false);
$('#soul-condition' + tableId + ' [name^=datetime][value=specific]').prop('checked', true);
var filterSo = {
id: id,
head: head,
prefix: head ? 'and' : 'and',
mode: 'date',
field: field,
type: 'specific',
value: value
}
_this.updateWhere(myTable, filterSo);
if (!id) {
$('#soul-condition' + tableId).data('id', filterSo.id)
}
if ($('.soul-edit-out').length > 0) {
$('.soul-edit-out li[data-id="' + filterSo.id + '"]').children('.item-value').html(filterSo.value)
}
if (refresh) {
_this.soulReload(myTable);
}
form.render('radio', 'orm');
}
});
form.on('radio(datetime' + tableId + ')', function (data) {
var id = $('#soul-condition' + tableId).data('id'),
head = $('#soul-condition' + tableId).data('head')
var filterSo = {
id: id,
head: head,
prefix: head ? 'and' : 'and',
mode: 'date',
field: field,
type: data.value,
value: $('#soul-condition' + tableId + ' .specific_value').val()
}
_this.updateWhere(myTable, filterSo);
if (!id) {
$('#soul-condition' + tableId).data('id', filterSo.id)
}
if ($('.soul-edit-out').length > 0) {
$('.soul-edit-out li[data-id="' + filterSo.id + '"]').children('.item-value').html(dateTimeItems[filterSo.type] || filterSo.value)
}
if (refresh) {
_this.soulReload(myTable);
}
});
form.render('radio', 'orm')
if (type === 'down') {
if (left + $('#soul-condition' + tableId).width() < documentWidth) {
animate = 'fadeInLeft'
} else {
left = left - $('#main-list' + tableId).width() - $('#soul-condition' + tableId).width();
animate = 'fadeInRight'
}
} else {
top = top - $('#soul-condition' + tableId).outerHeight() - 10;
}
$('#soul-condition' + tableId).css({'top': top, 'left': left})
.show().removeClass().addClass(animate + ' animated');
}
, bottomConditionHtml: function (bcHtml, filterSo, fieldMap, first) {
var _this = this,
isOr = filterSo.prefix === 'or',
field = filterSo.field;
if (filterSo.mode === 'group') {
if (filterSo.children && filterSo.children.length > 0) {
bcHtml.push('<div class="condition-item" data-id="' + filterSo.id + '" data-prefix="' + (filterSo.prefix || 'and') + '">');
if (!first) {
bcHtml.push('<div class="item-prefix layui-red">' + (isOr ? '' : '') + '</div> ');
}
for (var i = 0; i < filterSo.children.length; i++) {
_this.bottomConditionHtml(bcHtml, filterSo.children[i], fieldMap, i === 0);
}
bcHtml.push('<i class="condition-item-close soul-icon soul-icon-unfold" ></i>');
bcHtml.push('</div>')
}
return;
}
bcHtml.push('<div class="condition-item" data-field="' + field + '" data-id="' + filterSo.id + '" data-mode="' + filterSo.mode + '" data-type="' + filterSo.type + '" data-value="' + (typeof filterSo.value === 'undefined' ? '' : filterSo.value) + '" data-prefix="' + (filterSo.prefix || 'and') + '">');
if (!first) {
bcHtml.push('<div class="item-prefix layui-red">' + (isOr ? '' : '') + '</div> ');
}
bcHtml.push('<div class="item-field layui-firebrick">' + fieldMap[field].title + '</div> ');
bcHtml.push('<div class="item-type layui-deeppink">');
switch (filterSo.mode) {
case 'in':
bcHtml.push('筛选数据');
break;
case 'condition':
bcHtml.push(conditionChangeItems[filterSo.type]);
break;
case 'date':
bcHtml.push('选择日期');
break;
default:
bcHtml.push('未知');
break;
}
bcHtml.push('</div> ');
if (filterSo.type !== 'null' && filterSo.type !== 'notNull') {
bcHtml.push('<div class="item-value layui-blueviolet ' + (filterSo.mode === 'date' && filterSo.type !== 'specific') + '">');
switch (filterSo.mode) {
case 'in':
bcHtml.push('' + (filterSo.values ? filterSo.values.length : 0) + '条数据');
break;
case 'date':
bcHtml.push(filterSo.type === 'specific' ? filterSo.value || '请选择' : dateTimeItems[filterSo.type])
break;
case 'condition':
default:
bcHtml.push(typeof filterSo.value === 'undefined' || filterSo.value === '' ? '请输入...' : filterSo.value);
break;
}
bcHtml.push('</div>')
}
bcHtml.push('<i class="condition-item-close soul-icon soul-icon-unfold" ></i>');
bcHtml.push('</div>')
}
, renderBottomCondition: function (myTable) {
var _this = this,
where = where_cache[myTable.id] || {},
filterSos = where.filterSos ? JSON.parse(where.filterSos) : [],
tableFilterTypes = where.tableFilterType ? JSON.parse(where.tableFilterType) : {},
$table = $(myTable.elem),
tableId = myTable.id,
$bottomCondition = $table.next().children('.soul-bottom-contion'),
fieldMap = {}, bcHtml = [], curItems,
filterItems = myTable.filter ? myTable.filter.items || defaultFilterItems : defaultFilterItems,
columns = _this.getCompleteCols(myTable.cols);
for (var i = 0; i < columns.length; i++) {
if (columns[i].field && columns[i].filter) {
curItems = columns[i].filter.items || filterItems;
if (curItems.indexOf('data') !== -1 || curItems.indexOf('condition') !== -1) {
fieldMap[columns[i]['field']] = {
title: columns[i].title,
items: curItems
}
}
}
}
/**
* 一、拼装底部内容
*/
for (var i = 0; i < filterSos.length; i++) {
_this.bottomConditionHtml(bcHtml, filterSos[i], fieldMap, i === 0);
}
$bottomCondition.children('.condition-items').html(bcHtml.join(''))
/**
* 二、组装底部弹窗条件
*/
bcHtml = [];
// 1. prefix
if ($('#soul-bf-prefix' + tableId).length === 0) {
bcHtml.push('<div id="soul-bf-prefix' + tableId + '" style="display: none;"><ul>')
bcHtml.push('<li data-value="and">与</li>')
bcHtml.push('<li data-value="or">或</li>')
bcHtml.push('</ul></div>')
}
// 2. 列选择
if ($('#soul-bf-column' + tableId).length === 0) {
bcHtml.push('<div id="soul-bf-column' + tableId + '" style="display: none;"><ul>')
for (var field in fieldMap) {
bcHtml.push('<li data-field="' + field + '">' + fieldMap[field].title + '</li>')
}
bcHtml.push('</ul></div>')
}
// 3. 条件选择
if ($('#soul-bf-type' + tableId).length === 0) {
bcHtml.push('<div id="soul-bf-type' + tableId + '" style="display: none;"><ul>')
bcHtml.push('<li data-value="in" data-mode="in">筛选数据</li>')
bcHtml.push('<li data-value="all" data-mode="date">选择日期</li>')
for (var key in conditionChangeItems) {
bcHtml.push('<li data-value="' + key + '" data-mode="condition">' + conditionChangeItems[key] + '</li>')
}
bcHtml.push('</ul></div>')
}
// 4. 值选择
if ($('#soul-bf-cond2-dropList' + tableId).length === 0) {
bcHtml.push('<div id="soul-bf-cond2-dropList' + tableId + '" style="display: none;"><div class="filter-search"><input type="text" placeholder="关键字搜索" class="layui-input"></div><div class="check"><div class="multiOption" data-type="all"><i class="soul-icon">&#xe623;</i> 全选</div><div class="multiOption" data-type="none"><i class="soul-icon">&#xe63e;</i> 清空</div><div class="multiOption" data-type="reverse"><i class="soul-icon">&#xe614;</i>反选</div></div><ul></ul></div>')
}
$('body').append(bcHtml.join(''))
/**
* 三、底部弹窗事件
*/
// 1. prefix弹出事件
$bottomCondition.find('.item-prefix').off('click').on('click', function (e) {
e.stopPropagation();
$('#main-list' + tableId).hide();
_this.hideDropList(myTable);
_this.hideCondition(myTable);
_this.hideColumns(myTable);
_this.hideBfColumn(myTable);
_this.hideBfType(myTable);
var top = $(this).offset().top - $('#soul-bf-prefix' + tableId).outerHeight() - 10,
left = $(this).offset().left;
$('#soul-bf-prefix' + tableId).find('li.soul-bf-selected').removeClass('soul-bf-selected')
$('#soul-bf-prefix' + tableId)
.data('id', $(this).parent().data('id'))
.data('prefix', $(this).parent().data('prefix'))
.data('refresh', true)
.show()
.css({top: top, left: left})
.removeClass().addClass('fadeInUp animated')
.find('li[data-value="' + $(this).parent().data('prefix') + '"]')
.addClass('soul-bf-selected')
})
// 2. 弹出列选择
$bottomCondition.find('.item-field').off('click').on('click', function (e) {
e.stopPropagation();
$('#main-list' + tableId).hide();
_this.hideDropList(myTable);
_this.hideCondition(myTable);
_this.hideColumns(myTable);
_this.hideBfPrefix(myTable)
_this.hideBfType(myTable);
var top = $(this).offset().top - $('#soul-bf-column' + tableId).outerHeight() - 10,
left = $(this).offset().left;
$('#soul-bf-column' + tableId).find('li.soul-bf-selected').removeClass('soul-bf-selected')
$('#soul-bf-column' + tableId)
.data('field', $(this).parent().data('field'))
.data('id', $(this).parent().data('id'))
.data('mode', $(this).parent().data('mode'))
.data('group', $(this).parent().parent().data('id') || '')
.data('refresh', true)
.show()
.css({top: top, left: left})
.removeClass().addClass('fadeInUp animated')
.find('li[data-field="' + $(this).parent().data('field') + '"]')
.addClass('soul-bf-selected')
})
// 3. 弹出方式选择
$bottomCondition.find('.item-type').on('click', function (e) {
e.stopPropagation();
$('#main-list' + tableId).hide();
_this.hideDropList(myTable);
_this.hideCondition(myTable);
_this.hideColumns(myTable);
_this.hideBfColumn(myTable);
_this.hideBfPrefix(myTable);
var field = $(this).parent().data('field')
$('#soul-bf-type' + tableId + ' li').hide()
if (tableFilterTypes[field] && tableFilterTypes[field].indexOf('date') === 0) {
$('#soul-bf-type' + tableId + ' li[data-mode=date]').show()
}
if (fieldMap[field].items.indexOf('data') !== -1) {
$('#soul-bf-type' + tableId + ' li[data-mode=in]').show()
}
if (fieldMap[field].items.indexOf('condition') !== -1) {
$('#soul-bf-type' + tableId + ' li[data-mode=condition]').show()
}
var top = $(this).offset().top - $('#soul-bf-type' + tableId).outerHeight() - 10,
left = $(this).offset().left;
$('#soul-bf-type' + tableId).find('li.soul-bf-selected').removeClass('soul-bf-selected')
switch ($(this).parent().data('mode')) {
case 'in':
$('#soul-bf-type' + tableId).find('li[data-mode="in"]')
.addClass('soul-bf-selected')
break;
case 'date':
$('#soul-bf-type' + tableId).find('li[data-mode="date"]')
.addClass('soul-bf-selected')
case 'condition':
$('#soul-bf-type' + tableId).find('li[data-value="' + $(this).parent().data('type') + '"]')
.addClass('soul-bf-selected')
}
$('#soul-bf-type' + tableId)
.data('type', $(this).parent().data('type'))
.data('mode', $(this).parent().data('mode'))
.data('id', $(this).parent().data('id'))
.data('group', $(this).parent().parent().data('id') || '')
.data('refresh', true)
.show()
.css({top: top, left: left})
.removeClass().addClass('fadeInUp animated')
})
// 4. 弹出值选择
$bottomCondition.find('.item-value').on('click', function (e) {
e.stopPropagation();
$('#main-list' + tableId).hide();
_this.hideColumns(myTable);
_this.hideBfType(myTable);
_this.hideBfPrefix(myTable)
_this.hideBfColumn(myTable);
var top,
left = $(this).offset().left,
mode = $(this).parent().data('mode'),
field = $(this).parent().data('field'),
id = $(this).parent().data('id'),
head = $(this).parent().data('head'),
prefix = $(this).parent().data('prefix');
switch (mode) {
case 'in':
_this.hideCondition(myTable);
if (dorpListTimeOut) {
clearTimeout(dorpListTimeOut);
}
$('#soul-dropList' + tableId + '>.filter-search>input').val('');
$('#soul-dropList' + tableId).show();
$('#soulDropList' + tableId).find('.' + field + 'DropList li input[type=checkbox]:checked').prop('checked', false);
var filterSo = _this.getFilterSoById(filterSos, id);
for (var i = 0; i < filterSo.values.length; i++) {
$('#soulDropList' + tableId).find('.' + field + 'DropList li input[type=checkbox][value="' + filterSo.values[i] + '"]').prop('checked', true);
}
$('#soul-dropList' + tableId + '>ul').data('id', id).data('head', head).data('refresh', true).data('prefix', prefix).html($('#soulDropList' + tableId).find('.' + field + 'DropList li').clone());
form.render('checkbox', 'orm');
top = $(this).offset().top - $('#soul-dropList' + tableId).outerHeight() - 10;
$('#soul-dropList' + tableId).css({'top': top, 'left': left})
.show().removeClass().addClass('fadeInUp animated');
setTimeout(function () {
$('#soul-dropList' + tableId + '>.filter-search>input').focus() // 聚焦搜索框
}, 1);
// 监听筛选数据
var liClick = true;
form.on('checkbox(soulDropList' + tableId + ')', function (data) {
liClick = false;
_this.updateDropList(myTable, field);
});
$('#soul-dropList' + tableId + '>ul>li[data-value]').on('click', function () {
if (liClick) {
$(this).find('div.layui-form-checkbox').trigger('click');
}
liClick = true;
})
break;
case 'date':
_this.hideDropList(myTable);
if (conditionTimeOut) {
clearTimeout(conditionTimeOut);
}
var filterSo = _this.getFilterSoById(filterSos, id),
top = $(this).offset().top - 10;
_this.showDate(myTable, field, filterSo, "fadeInUp", top, left, "up", true);
break;
default:
_this.hideDropList(myTable);
if (conditionTimeOut) {
clearTimeout(conditionTimeOut);
}
var obj = this,
value = $(this).parents('.condition-item:eq(0)').data('value');
$(obj).hide();
$(obj).after('<div><input style="height: 25px;" class="layui-input tempValue" value="" /></div>')
$(obj).next().children().val(value).select().on('keydown', function (e) {
if (e.keyCode === 13) {
$(this).blur();
}
}).on('blur', function () {
var newValue = $(this).val();
$(obj).html(typeof newValue === 'undefined' || newValue === '' ? '请输入...' : newValue);
$(obj).show();
$(this).parent().remove()
if (newValue !== value) {
_this.updateWhere(myTable, {
id: id,
value: newValue
})
_this.soulReload(myTable);
}
})
break;
}
})
/**
* 三、选择事件
*/
// 1. 选择prefix
$('#soul-bf-prefix' + tableId + '>ul>li').off('click').on('click', function () {
var id = $(this).parent().parent().data('id'),
newPrefix = $(this).data('value'),
oldPrefix = $(this).parent().parent().data('prefix'),
refresh = $(this).parent().parent().data('refresh');
if (oldPrefix !== newPrefix) {
_this.updateWhere(myTable, {
id: id,
prefix: newPrefix
});
if (refresh === true) {
_this.soulReload(myTable);
}
}
})
// 1. 选择列
$('#soul-bf-column' + tableId + '>ul>li').off('click').on('click', function () {
var oldField = $(this).parent().parent().data('field'),
newField = $(this).data('field'),
mode = $(this).parent().parent().data('mode'),
group = $(this).parent().parent().data('group'),
refresh = $(this).parent().parent().data('refresh');
if (oldField !== newField) {
var filterSo = {
id: $(this).parent().parent().data('id'),
field: newField
}
if (fieldMap[newField].items.indexOf(modeMapItems[mode]) === -1) {
$.extend(filterSo, $.extend({}, revertMode[modeMapItems[mode]],
revertMode[modeMapItems[mode]].mode === 'condition' && _this.startsWith(tableFilterTypes[newField], 'date')
? {
mode: 'date',
type: 'all'
} : {}))
} else {
// 重置values值
if (mode === 'in') {
$.extend(filterSo, {
values: []
})
} else if (mode === 'date' && !(_this.startsWith(tableFilterTypes[newField], 'date'))) {
$.extend(filterSo, {
mode: 'condition',
type: 'eq',
value: ''
})
} else if (mode !== 'date' && _this.startsWith(tableFilterTypes[newField], 'date')) {
$.extend(filterSo, {
mode: 'date',
type: 'all'
})
}
}
// 如果是头部条件,选择列是清除
if (group) {
_this.updateWhere(myTable, {
id: group,
head: false
})
}
_this.updateWhere(myTable, filterSo);
if ($('.soul-edit-out').length > 0) {
$('.soul-edit-out li[data-id="' + filterSo.id + '"]').data(filterSo).children('.item-field').html(fieldMap[newField].title);
if (filterSo.mode === 'in') {
$('.soul-edit-out li[data-id="' + filterSo.id + '"]').children('.item-type').html('筛选数据')
$('.soul-edit-out li[data-id="' + filterSo.id + '"]').children('.item-value').html('共0条数据')
} else if (mode !== filterSo.mode) {
if (filterSo.mode === 'date') {
$('.soul-edit-out li[data-id="' + filterSo.id + '"]').children('.item-type').html('选择日期')
$('.soul-edit-out li[data-id="' + filterSo.id + '"]').children('.item-value').html(dateTimeItems[filterSo.type])
} else if (filterSo.mode === 'condition') {
$('.soul-edit-out li[data-id="' + filterSo.id + '"]').children('.item-type').html(conditionChangeItems[filterSo.type])
$('.soul-edit-out li[data-id="' + filterSo.id + '"]').children('.item-value').html(filterSo.value === '' ? '请输入...' : filterSo.value)
}
}
}
if (refresh === true) {
_this.soulReload(myTable);
}
}
})
// 2. 选择类型
$('#soul-bf-type' + tableId + '>ul>li').off('click').on('click', function () {
var newType = $(this).data('value') + "" // 引号修复为空(null值)传递问题
, newMode = $(this).data('mode')
, type = $(this).parent().parent().data('type')
, mode = $(this).parent().parent().data('mode')
, group = $(this).parent().parent().data('group')
, refresh = $(this).parent().parent().data('refresh')
if (type !== newType) {
var filterSo = {
id: $(this).parent().parent().data('id'),
type: newType,
mode: newMode
}
if (mode !== newMode) {
$.extend(filterSo, {
value: '',
values: []
})
}
// 如果是头部条件,选择列是清除
if (group && newMode === 'in') {
_this.updateWhere(myTable, {
id: group,
head: false
})
}
_this.updateWhere(myTable, filterSo)
if ($('.soul-edit-out').length > 0) {
$('.soul-edit-out li[data-id="' + filterSo.id + '"]').data(filterSo).children('.item-value').show();
$('.soul-edit-out li[data-id="' + filterSo.id + '"]').data(filterSo).children('.item-type').html(conditionChangeItems[newType] || (newMode === 'in' ? '筛选数据' : '选择日期'));
switch (newMode) {
case 'in':
$('.soul-edit-out li[data-id="' + filterSo.id + '"]').data(filterSo).children('.item-value').html('共0条数据');
break;
case 'date':
$('.soul-edit-out li[data-id="' + filterSo.id + '"]').data(filterSo).children('.item-value').html(dateTimeItems[newType]);
break;
case 'condition':
if (mode !== newMode) {
$('.soul-edit-out li[data-id="' + filterSo.id + '"]').data(filterSo).children('.item-value').html('请输入...');
}
$('.soul-edit-out li[data-id="' + filterSo.id + '"]').data(filterSo).children('.item-value')[newType === 'null' || newType === 'notNull' ? 'hide' : 'show']()
break;
}
}
// 是否立即更新
if (refresh === true) {
_this.soulReload(myTable);
}
}
})
/**
* 五、底部筛选条件删除事件
*/
$bottomCondition.find('.condition-items .condition-item .condition-item-close').on('click', function () {
_this.updateWhere(myTable, {
id: $(this).parents('.condition-item:eq(0)').data('id'),
delete: true
})
_this.soulReload(myTable);
})
}
/**
* 导出 excel 文件
* @param myTable
* @param curExcel
*/
, export: function (myTable, curExcel) {
if (typeof myTable === 'string') {
myTable = table_cache[myTable] // tableId 转 myTable
}
var loading = layer.msg('文件下载中', {
icon: 16
, time: -1
, anim: -1
, fixed: false
});
var cols = this.deepClone(myTable.cols)
, style = myTable.elem.next().find('style')[0]
, sheet = style.sheet || style.styleSheet || {}
, rules = sheet.cssRules || sheet.rules;
layui.each(rules, function (i, item) {
if (item.style.width) {
var keys = item.selectorText.split('-');
cols[keys[3]][keys[4]]['width'] = parseInt(item.style.width)
}
})
var data = JSON.parse(JSON.stringify(myTable.data || cache[myTable.id])),
showField = {},
widths = {},
mergeArrays = [], // 合并配置
heightConfig = {},
$table = $(myTable.elem),
$tableBody = $table.next().children('.layui-table-box').children('.layui-table-body').children('table'),
$tableTotal = myTable.totalRow ? $table.next().children('.layui-table-total').children(":first") : null,
finalExcel = Object.assign({}, myTable.excel, curExcel);
var filename = finalExcel.filename ? (typeof finalExcel.filename === 'function' ? finalExcel.filename.call(this) : finalExcel.filename) : '表格数据.xlsx',
checked = finalExcel.checked === true,
curPage = finalExcel.curPage === true,
customColumns = finalExcel.columns,
totalRow = finalExcel.totalRow,
type = filename.substring(filename.lastIndexOf('.') + 1, filename.length),
tableStartIndex = finalExcel.add && finalExcel.add.top && Array.isArray(finalExcel.add.top.data) ? finalExcel.add.top.data.length + 1 : 1, //表格内容从哪一行开始
bottomLength = finalExcel.add && finalExcel.add.bottom && Array.isArray(finalExcel.add.bottom.data) ? finalExcel.add.bottom.data.length : 0,// 底部自定义行数
i, j, k;
if (finalExcel.data){
if(Array.isArray(finalExcel.data)) {
data = finalExcel.data
} else {
console.error('导出指定数据 data 不符合数组格式', finalExcel.data)
layer.close(loading)
return;
}
} else if (checked) { // 获取选中行数据
// data = table.checkStatus(myTable.id).data;
data = []
if (cache[myTable.id] && cache[myTable.id].length > 0) {
for (i = 0; i < cache[myTable.id].length; i++) {
if (cache[myTable.id][i][table.config.checkName]) {
data.push(cache[myTable.id][i])
}
}
}
} else if (curPage) {
data = layui.table.cache[myTable.id]
} else if (myTable.url && myTable.page) {
var ajaxStatus = true;
var searchParam = isFilterCache[myTable.id] ? where_cache[myTable.id] : table_cache[myTable.id].where;
if (myTable.contentType && myTable.contentType.indexOf("application/json") == 0) { //提交 json 格式
searchParam = JSON.stringify(searchParam);
}
$.ajax({
url: myTable.url,
data: searchParam,
dataType: 'json',
method: myTable.method || 'post',
async: false,
cache: false,
headers: myTable.headers || {},
contentType: myTable.contentType,
success: function (res) {
if (typeof myTable.parseData === 'function') {
res = myTable.parseData(res) || res;
}
//检查数据格式是否符合规范
if (res[myTable.response.statusName] != myTable.response.statusCode) {
layer.msg('返回的数据不符合规范,正确的成功状态码应为:"' + myTable.response.statusName + '": ' + myTable.response.statusCode, {
icon: 2,
anim: 6
});
} else {
data = res[myTable.response.dataName]
}
},
error: function (res) {
layer.msg('请求异常!', {icon: 2, anim: 6});
ajaxStatus = false;
}
})
if (!ajaxStatus) {
return;
}
} else {
var $sortDoom = $table.next().children('.layui-table-box').children('.layui-table-header').find('.layui-table-sort[lay-sort$="sc"]:eq(0)')
if ($sortDoom.length > 0) {
var sortField = $sortDoom.parent().parent().data('field');
var sortOrder = $sortDoom.attr('lay-sort');
switch (sortOrder) {
case 'asc':
data = layui.sort(data, sortField);
break;
case 'desc':
data = layui.sort(data, sortField, true);
break;
default:
break;
}
}
}
// 制定显示列和顺序
var tempArray, cloneCol, columnsMap = [], curRowUnShowCount;
for (i = 0; i < cols.length; i++) {
curRowUnShowCount = 0;
for (j = 0; j < cols[i].length; j++) {
if (!cols[i][j].exportHandled) {
if (cols[i][j].rowspan > 1) {
if ((cols[i][j].field || cols[i][j].type === 'numbers') && !cols[i][j].hide) {
mergeArrays.push([numberToLetter(j + 1 - curRowUnShowCount) + (i + tableStartIndex), numberToLetter(j + 1 - curRowUnShowCount) + (i + parseInt(cols[i][j].rowspan) + tableStartIndex - 1)])
} else {
curRowUnShowCount++;
}
cloneCol = this.deepClone(cols[i][j])
cloneCol.exportHandled = true;
k = i + 1;
while (k < cols.length) {
cols[k].splice(j, 0, cloneCol)
k++
}
}
if (cols[i][j].colspan > 1) {
mergeArrays.push([numberToLetter(j + 1 - curRowUnShowCount) + (i + tableStartIndex), numberToLetter(j + parseInt(cols[i][j].colspan) - curRowUnShowCount) + (i + tableStartIndex)])
cloneCol = this.deepClone(cols[i][j])
cloneCol.exportHandled = true;
for (k = 1; k < cols[i][j].colspan; k++) {
cols[i].splice(j, 0, cloneCol)
}
j = j + parseInt(cols[i][j].colspan) - 1
}
} else if (!((cols[i][j].field || cols[i][j].type === 'numbers') && !cols[i][j].hide)) {
curRowUnShowCount++;
}
}
}
var columns = cols[cols.length - 1]; // 获取真实列
// 处理数据
for (i = 0; i < data.length; i++) {
for (j = 0; j < columns.length; j++) {
if ((columns[j].field || columns[j].type === 'numbers') && (customColumns && Array.isArray(customColumns) || !columns[j].hide)) {
data[i][columns[j].key] = data[i][columns[j].field || columns[j]['LAY_TABLE_INDEX']]
}
}
}
// 处理合计行
if (totalRow !== false && myTable.totalRow) {
var obj = {}, totalRows = {};
if (typeof totalRow === 'object' && totalRow.type === 'origin') {
// 通过 dom 解析
for (i = 0; i < columns.length; i++) {
if (columns[i].field) {
obj[columns[i].key] = $tableTotal.find('[data-field="'+columns[i].field+'"]').text().trim()
}
}
data.push(obj);
} else {
// 通过数据解析
for (i = 0; i < columns.length; i++) {
if (columns[i].totalRowText) {
obj[columns[i].key] = columns[i].totalRowText
} else if (columns[i].totalRow) {
totalRows[columns[i].key] = 0
}
}
if (JSON.stringify(totalRows) !== '{}') {
for (i = 0; i < data.length; i++) {
for (var key in totalRows) {
totalRows[key] = (parseFloat(totalRows[key]) + (parseFloat(data[i][key]) || 0)).toFixed(2)
}
}
}
data.push(Object.assign(obj, totalRows));
}
}
if (customColumns && Array.isArray(customColumns)) {
// 自定义表头
var tempCustomColumns = [];
tempArray = {};
mergeArrays = []; // 重置表头合并列
columnsMap[0] = {};
for (i = 0; i < customColumns.length; i++) {
for (j = 0; j < columns.length; j++) {
if (columns[j].field === customColumns[i]) {
columns[j].hide = false
tempCustomColumns.push(columns[j]);
columnsMap[0][columns[j].key] = columns[j];
tempArray[columns[j].key] = $('<div>'+columns[j].title+'</div>').text()
break;
}
}
}
columns = tempCustomColumns;
data.splice(0, 0, tempArray)
} else {
// 拼接表头数据
for (i = 0; i < cols.length; i++) {
columnsMap[i] = {}
tempArray = {}
for (j = 0; j < cols[i].length; j++) {
columnsMap[i][cols[cols.length - 1][j].key] = cols[i][j];
tempArray[cols[cols.length - 1][j].key] = $('<div>'+cols[i][j].title+'</div>').text()
}
data.splice(i, 0, tempArray)
}
}
//添加自定义内容
if (finalExcel.add) {
var addTop = finalExcel.add.top,
addBottom = finalExcel.add.bottom,
startPos, endPos, jumpColsNum;
if (addTop && Array.isArray(addTop.data) && addTop.data.length > 0) {
for (i = 0; i < addTop.data.length; i++) {
tempArray = {}, jumpColsNum = 0;
for (j = 0; j < (addTop.data[i].length > columns.length ? addTop.data[i].length : columns.length); j++) {
if ((columns[j].field || columns[j].type === 'numbers') && !columns[j].hide) {
tempArray[columns[j] ? columns[j].key : j + ''] = addTop.data[i][j - jumpColsNum] || ''
} else {
jumpColsNum++
}
}
data.splice(i, 0, tempArray);
}
if (Array.isArray(addTop.heights) && addTop.heights.length > 0) {
for (i = 0; i < addTop.heights.length; i++) {
heightConfig[i] = addTop.heights[i]
}
}
if (Array.isArray(addTop.merge) && addTop.merge.length > 0) {
for (i = 0; i < addTop.merge.length; i++) {
if (addTop.merge[i].length === 2) {
startPos = addTop.merge[i][0].split(',');
endPos = addTop.merge[i][1].split(',');
mergeArrays.push([numberToLetter(startPos[1]) + startPos[0], numberToLetter(endPos[1]) + endPos[0]])
}
}
}
}
if (addBottom && Array.isArray(addBottom.data) && addBottom.data.length > 0) {
for (i = 0; i < addBottom.data.length; i++) {
tempArray = {}, jumpColsNum = 0;
for (j = 0; j < (addBottom.data[i].length > columns.length ? addBottom.data[i].length : columns.length); j++) {
if ((columns[j].field || columns[j].type === 'numbers') && !columns[j].hide) {
tempArray[columns[j] ? columns[j].key : j + ''] = addBottom.data[i][j - jumpColsNum] || ''
} else {
jumpColsNum++
}
}
data.push(tempArray);
}
if (Array.isArray(addBottom.heights) && addBottom.heights.length > 0) {
for (i = 0; i < addBottom.heights.length; i++) {
heightConfig[data.length - addBottom.data.length + i] = addBottom.heights[i]
}
}
if (Array.isArray(addBottom.merge) && addBottom.merge.length > 0) {
for (i = 0; i < addBottom.merge.length; i++) {
if (addBottom.merge[i].length === 2) {
startPos = addBottom.merge[i][0].split(',');
endPos = addBottom.merge[i][1].split(',');
mergeArrays.push([numberToLetter(startPos[1]) + (data.length - addBottom.data.length + parseInt(startPos[0])), numberToLetter(endPos[1]) + (data.length - addBottom.data.length + parseInt(endPos[0]))])
}
}
}
}
}
var index = 0, alignTrans = {'left': 'left', 'center': 'center', 'right': 'right'},
borderTypes = ['top', 'bottom', 'left', 'right'];
for (i = 0; i < columns.length; i++) {
if ((columns[i].field || columns[i].type === 'numbers') && !columns[i].hide) {
if (columns[i].width) {
widths[String.fromCharCode(64 + parseInt(++index))] = columns[i].width
}
showField[columns[i].key] = function (field, line, data, curIndex) {
var bgColor = 'ffffff', color = '000000', family = 'Calibri', size = 12, cellType = 's',
bodyIndex = curIndex - (customColumns ? 1 : cols.length) - tableStartIndex + 1,
border = {
top: {
style: 'thin',
color: {indexed: 64}
},
bottom: {
style: 'thin',
color: {indexed: 64}
},
left: {
style: 'thin',
color: {indexed: 64}
},
right: {
style: 'thin',
color: {indexed: 64}
}
}
if (finalExcel.border) {
for (j = 0; j < borderTypes.length; j++) {
if (finalExcel.border[borderTypes[j]]) {
border[borderTypes[j]].style = finalExcel.border[borderTypes[j]].style || border[borderTypes[j]].style
border[borderTypes[j]].color = handleRgb(finalExcel.border[borderTypes[j]].color) || border[borderTypes[j]].color
} else if (finalExcel.border['color'] || finalExcel.border['style']) {
border[borderTypes[j]].style = finalExcel.border['style'] || border[borderTypes[j]].style
border[borderTypes[j]].color = handleRgb(finalExcel.border['color']) || border[borderTypes[j]].color
}
}
}
if (curIndex < tableStartIndex - 1 || curIndex >= data.length - bottomLength) {
return {
v: line[field] || '',
s: {// s 代表样式
alignment: {
horizontal: 'center',
vertical: 'center'
},
font: {name: family, sz: size, color: {rgb: color}},
fill: {
fgColor: {rgb: bgColor, bgColor: {indexed: 64}}
},
border: border
},
t: cellType
}
} else if (bodyIndex < 0) {
// 头部样式
bgColor = 'C7C7C7';
if (finalExcel.head) {
bgColor = finalExcel.head.bgColor || bgColor;
color = finalExcel.head.color || color;
family = finalExcel.head.family || family;
size = finalExcel.head.size || size;
}
} else {
// 默认全局字体样式
if (finalExcel.font) {
bgColor = finalExcel.font.bgColor || bgColor;
color = finalExcel.font.color || color;
family = finalExcel.font.family || family;
size = finalExcel.font.size || size;
}
// 默认全局边框样式
if (finalExcel.border) {
for (j = 0; j < borderTypes.length; j++) {
if (finalExcel.border[borderTypes[j]]) {
border[borderTypes[j]].style = finalExcel.border[borderTypes[j]].style || border[borderTypes[j]].style
border[borderTypes[j]].color = handleRgb(finalExcel.border[borderTypes[j]].color) || border[borderTypes[j]].color
} else if (finalExcel.border['color'] || finalExcel.border['style']) {
border[borderTypes[j]].style = finalExcel.border['style'] || border[borderTypes[j]].style
border[borderTypes[j]].color = handleRgb(finalExcel.border['color']) || border[borderTypes[j]].color
}
}
}
// 列上配置了自定义样式
if (columnsMap[columnsMap.length - 1][field].excel) {
var colExcel = typeof columnsMap[columnsMap.length - 1][field].excel === 'function' ? columnsMap[columnsMap.length - 1][field].excel.call(this, line, bodyIndex, data.length - cols.length - tableStartIndex + 1 - bottomLength) : columnsMap[columnsMap.length - 1][field].excel
if (colExcel) {
bgColor = colExcel.bgColor || bgColor;
color = colExcel.color || color;
family = colExcel.family || family;
size = colExcel.size || size;
cellType = colExcel.cellType || cellType;
if (colExcel.border) {
for (j = 0; j < borderTypes.length; j++) {
if (colExcel.border[borderTypes[j]]) {
border[borderTypes[j]].style = colExcel.border[borderTypes[j]].style || border[borderTypes[j]].style
border[borderTypes[j]].color = handleRgb(colExcel.border[borderTypes[j]].color) || border[borderTypes[j]].color
} else if (colExcel.border['color'] || colExcel.border['style']) {
border[borderTypes[j]].style = colExcel.border['style'] || border[borderTypes[j]].style
border[borderTypes[j]].color = handleRgb(colExcel.border['color']) || border[borderTypes[j]].color
}
}
}
}
}
}
function handleNull(val) {
if (typeof val === 'undefined' || val === null) {
return ""
}
return val;
}
var value = bodyIndex >= 0 && columnsMap[columnsMap.length - 1][field].templet ?
typeof columnsMap[columnsMap.length - 1][field].templet === 'function' ?
$('<div>' + columnsMap[columnsMap.length - 1][field].templet(line) + '</div>').find(':input').length === 0 ? $('<div>' + columnsMap[columnsMap.length - 1][field].templet(line) + '</div>').text() : $tableBody.children('tbody').children('tr[data-index=' + bodyIndex + ']').children('td[data-field="' + field + '"]').find(':input').val() || handleNull(line[field])
: $('<div>' + laytpl($(columnsMap[columnsMap.length - 1][field].templet).html() || String(columnsMap[columnsMap.length - 1][field].templet)).render(line) + '</div>').find(':input').length === 0 ? $('<div>' + laytpl($(columnsMap[columnsMap.length - 1][field].templet).html() || String(columnsMap[columnsMap.length - 1][field].templet)).render(line) + '</div>').text() : $tableBody.children('tbody').children('tr[data-index=' + bodyIndex + ']').children('td[data-field="' + field + '"]').find(':input').val() || handleNull(line[field])
: bodyIndex >= 0 && columnsMap[columnsMap.length - 1][field].type === 'numbers' ? bodyIndex + 1 : handleNull(line[field]);
return {
v: value,// v 代表单元格的值
s: {// s 代表样式
alignment: {
horizontal: columnsMap[bodyIndex < -1 ? curIndex - tableStartIndex + 1 : columnsMap.length - 1][field].align ? alignTrans[columnsMap[bodyIndex < -1 ? curIndex - tableStartIndex + 1 : columnsMap.length - 1][field].align] : 'top',
vertical: 'center'
},
font: {name: family, sz: size, color: {rgb: color}},
fill: {
fgColor: {rgb: bgColor, bgColor: {indexed: 64}}
},
border: border
},
t: UNHANDLED_VALUES.indexOf(value) === -1 ? cellType : 's'
};
}
}
}
excel.exportExcel({
sheet1: excel.filterExportData(data, showField)
}, filename, type, {
extend: {
'!cols': excel.makeColConfig(widths, 80),
'!merges': excel.makeMergeConfig(mergeArrays),
'!rows': excel.makeRowConfig(heightConfig, 16)
}
});
layer.close(loading);
// 合成 excel.js 识别的 rgb
function handleRgb(rgb) {
return rgb ? {rgb: rgb} : rgb
}
function numberToLetter(num) {
var result = [];
while (num) {
var t = num % 26;
if (!t) {
t = 26;
--num;
}
// Polyfill 兼容旧浏览器
if (!String.fromCodePoint) (function (stringFromCharCode) {
var fromCodePoint = function (_) {
var codeUnits = [], codeLen = 0, result = "";
for (var index = 0, len = arguments.length; index !== len; ++index) {
var codePoint = +arguments[index];
// correctly handles all cases including `NaN`, `-Infinity`, `+Infinity`
// The surrounding `!(...)` is required to correctly handle `NaN` cases
// The (codePoint>>>0) === codePoint clause handles decimals and negatives
if (!(codePoint < 0x10FFFF && (codePoint >>> 0) === codePoint))
throw RangeError("Invalid code point: " + codePoint);
if (codePoint <= 0xFFFF) { // BMP code point
codeLen = codeUnits.push(codePoint);
} else { // Astral code point; split in surrogate halves
// https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
codePoint -= 0x10000;
codeLen = codeUnits.push(
(codePoint >> 10) + 0xD800, // highSurrogate
(codePoint % 0x400) + 0xDC00 // lowSurrogate
);
}
if (codeLen >= 0x3fff) {
result += stringFromCharCode.apply(null, codeUnits);
codeUnits.length = 0;
}
}
return result + stringFromCharCode.apply(null, codeUnits);
};
try { // IE 8 only supports `Object.defineProperty` on DOM elements
Object.defineProperty(String, "fromCodePoint", {
"value": fromCodePoint, "configurable": true, "writable": true
});
} catch (e) {
String.fromCodePoint = fromCodePoint;
}
}(String.fromCharCode));
result.push(String.fromCodePoint(t + 64));
if (!String.fromCodePoint) (function (stringFromCharCode) {
var fromCodePoint = function (_) {
var codeUnits = [], codeLen = 0, result = "";
for (var index = 0, len = arguments.length; index !== len; ++index) {
var codePoint = +arguments[index];
// correctly handles all cases including `NaN`, `-Infinity`, `+Infinity`
// The surrounding `!(...)` is required to correctly handle `NaN` cases
// The (codePoint>>>0) === codePoint clause handles decimals and negatives
if (!(codePoint < 0x10FFFF && (codePoint >>> 0) === codePoint))
throw RangeError("Invalid code point: " + codePoint);
if (codePoint <= 0xFFFF) { // BMP code point
codeLen = codeUnits.push(codePoint);
} else { // Astral code point; split in surrogate halves
// https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
codePoint -= 0x10000;
codeLen = codeUnits.push(
(codePoint >> 10) + 0xD800, // highSurrogate
(codePoint % 0x400) + 0xDC00 // lowSurrogate
);
}
if (codeLen >= 0x3fff) {
result += stringFromCharCode.apply(null, codeUnits);
codeUnits.length = 0;
}
}
return result + stringFromCharCode.apply(null, codeUnits);
};
try { // IE 8 only supports `Object.defineProperty` on DOM elements
Object.defineProperty(String, "fromCodePoint", {
"value": fromCodePoint, "configurable": true, "writable": true
});
} catch (e) {
String.fromCodePoint = fromCodePoint;
}
}(String.fromCharCode));
num = ~~(num / 26);
}
return result.reverse().join('');
}
},
startsWith: function (content, str) {
var reg = new RegExp("^" + str);
return content && reg.test(content);
},
// 深度克隆-不丢失方法
deepClone: function (obj) {
var newObj = Array.isArray(obj) ? [] : {}
if (obj && typeof obj === "object") {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
newObj[key] = (obj && typeof obj[key] === 'object') ? this.deepClone(obj[key]) : obj[key];
}
}
}
return newObj
},
deepStringify: function (obj) {
var JSON_SERIALIZE_FIX = {
PREFIX: "[[JSON_FUN_PREFIX_",
SUFFIX: "_JSON_FUN_SUFFIX]]"
};
return JSON.stringify(obj, function (key, value) {
if (typeof value === 'function') {
return JSON_SERIALIZE_FIX.PREFIX + value.toString() + JSON_SERIALIZE_FIX.SUFFIX;
}
return value;
});
},
/* layui table 中原生的方法 */
getScrollWidth: function (elem) {
var width = 0;
if (elem) {
width = elem.offsetWidth - elem.clientWidth;
} else {
elem = document.createElement('div');
elem.style.width = '100px';
elem.style.height = '100px';
elem.style.overflowY = 'scroll';
document.body.appendChild(elem);
width = elem.offsetWidth - elem.clientWidth;
document.body.removeChild(elem);
}
return width;
}
, getCompleteCols: function (origin) {
var cols = this.deepClone(origin);
var i, j, k, cloneCol;
for (i = 0; i < cols.length; i++) {
for (j = 0; j < cols[i].length; j++) {
if (!cols[i][j].exportHandled) {
if (cols[i][j].rowspan > 1) {
cloneCol = this.deepClone(cols[i][j])
cloneCol.exportHandled = true;
k = i + 1;
while (k < cols.length) {
cols[k].splice(j, 0, cloneCol)
k++
}
}
if (cols[i][j].colspan > 1) {
cloneCol = this.deepClone(cols[i][j])
cloneCol.exportHandled = true;
for (k = 1; k < cols[i][j].colspan; k++) {
cols[i].splice(j, 0, cloneCol)
}
j = j + parseInt(cols[i][j].colspan) - 1
}
}
}
}
return cols[cols.length - 1];
}
, parseTempData: function (item3, content, tplData, text) { //表头数据、原始内容、表体数据、是否只返回文本
var str = item3.templet ? function () {
return typeof item3.templet === 'function'
? item3.templet(tplData)
: laytpl($(item3.templet).html() || String(content)).render(tplData)
}() : content;
return text ? $('<div>' + str + '</div>').text() : str;
}
, cache: cache
};
// 输出
exports('tableFilter', mod);
});
/**
*
* @name: 子表格扩展
* @author: yelog
* @link: https://github.com/yelog/layui-soul-table
* @license: MIT
* @version: v1.6.4
*/
layui.define(['table'], function (exports) {
var $ = layui.jquery;
// 封装方法
var mod = {
/**
* 渲染入口
* @param myTable
*/
render: function (myTable) {
var tableBox = $(myTable.elem).next().children('.layui-table-box'),
$main = $(tableBox.children('.layui-table-body').children('table').children('tbody').children('tr').toArray().reverse()),
$fixLeft = $(tableBox.children('.layui-table-fixed-l').children('.layui-table-body').children('table').children('tbody').children('tr').toArray().reverse()),
$fixRight = $(tableBox.children('.layui-table-fixed-r').children('.layui-table-body').children('table').children('tbody').children('tr').toArray().reverse()),
mergeRecord = {};
layui.each(myTable.cols, function (i1, item1) {
layui.each(item1, function (i2, item2) {
if (item2.merge && item2.field) {
var mergeField = [item2.field];
if (item2.merge !== true) {
if (typeof item2.merge === 'string') {
mergeField = [item2.merge]
} else {
mergeField = item2.merge
}
}
mergeRecord[myTable.index + '-' + i1 + '-' + i2] = {mergeField: mergeField, rowspan: 1}
}
})
})
$main.each(function (i) {
for (var item in mergeRecord) {
if (i === $main.length - 1 || isMaster(i, item)) {
var tdHeight = $(this).children('[data-key="' + item + '"]').outerHeight(), patchHeight = 0; // 获取td高度
if ($main.eq(i).data('index') === 0) {
patchHeight = 1
}
$(this).children('[data-key="' + item + '"]').attr('rowspan', mergeRecord[item].rowspan).css({
'position': 'static',
'height': tdHeight * mergeRecord[item].rowspan + patchHeight
}).children().css({
height: 'auto',
'white-space': 'normal',
'max-height': tdHeight * mergeRecord[item].rowspan + patchHeight - 10
});
$fixLeft.eq(i).children('[data-key="' + item + '"]').attr('rowspan', mergeRecord[item].rowspan).css({
'position': 'static',
'height': tdHeight * mergeRecord[item].rowspan + patchHeight
}).children().css({
height: 'auto',
'white-space': 'normal',
'max-height': tdHeight * mergeRecord[item].rowspan + patchHeight - 10
});
$fixRight.eq(i).children('[data-key="' + item + '"]').attr('rowspan', mergeRecord[item].rowspan).css({
'position': 'static',
'height': tdHeight * mergeRecord[item].rowspan + patchHeight
}).children().css({
height: 'auto',
'white-space': 'normal',
'max-height': tdHeight * mergeRecord[item].rowspan + patchHeight - 10
});
mergeRecord[item].rowspan = 1;
} else {
$(this).children('[data-key="' + item + '"]').remove();
$fixLeft.eq(i).children('[data-key="' + item + '"]').remove();
$fixRight.eq(i).children('[data-key="' + item + '"]').remove();
mergeRecord[item].rowspan += 1;
}
}
})
function isMaster(index, item) {
var mergeField = mergeRecord[item].mergeField;
var dataLength = layui.table.cache[myTable.id].length;
for (var i = 0; i < mergeField.length; i++) {
if (layui.table.cache[myTable.id][dataLength - 2 - index][mergeField[i]]
!== layui.table.cache[myTable.id][dataLength - 1 - index][mergeField[i]]) {
return true;
}
}
return false;
}
}
};
// 输出
exports('tableMerge', mod);
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>解析管理</title>
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<link rel="stylesheet" href="/static/plugin/layui/css/layui.css">
<link rel="stylesheet" href="/static/plugin/layui/ext/soulTable/soulTable.css" media="all"/>
</head>
<body>
<table id="myTable" ></table>
<script type="text/html" id="toolbar">
<div>
<!-- <button class="layui-btn layui-btn-sm" lay-event="clearFilter">清除所有筛选条件</button>-->
<button class="layui-btn layui-btn-sm" lay-event="getData">获取当前页数据</button>
</div>
</script>
<script type="text/html" id="bar">
<a class="layui-btn layui-btn-xs" lay-event="set_top"></a>
<a class="layui-btn layui-btn-xs" lay-event="set_bottom"></a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"></a>
</script>
<script src="/static/plugin/layui/layui.js"></script>
<script>
// 自定义模块
layui.config({
base: '/static/plugin/layui/ext/', // 模块目录
version: 'v1.6.4'
}).extend({
soulTable: 'soulTable/soulTable',
tableChild: 'soulTable/tableChild',
tableMerge: 'soulTable/tableMerge',
tableFilter: 'soulTable/tableFilter',
excel: 'soulTable/excel',
});
layui.use(['form', 'table','soulTable'], function () {
var table = layui.table, soulTable = layui.soulTable;
soulTable.config({
rowDrag: true
});
// 后台分页
table.render({
elem: '#myTable'
,id: 'myTable'
,url: '/layui/api/jx_list'
,height: 1000
,toolbar: '#toolbar'
,page: true
,limit:100
,limits:[20,40,60,80,100,150,200,300,500]
,cols: [[
{type: 'checkbox', fixed: 'left'},
{field: 'name', title: '名称', width: 200, sort: true, filter: true},
{field: 'url', title: '接口', minWidth: 200, sort: true, filter: true},
{field: 'type', title: '类型', width: 100 , filter: true},
// {field: 'header', title: '请求头', width: 112, filter: {split:','}, sort:true},
{field: 'header', title: '请求头', width: 200, sort:true},
{field: 'ext', title: '扩展信息', minWidth: 200, sort:true},
{title: '操作', width: 156, fixed: 'right', templet: '#bar'}
]]
,done: function () {
soulTable.render(this)
}
});
// 工具栏事件
table.on('toolbar(myTable)', function(obj){
var id = obj.config.id;
console.log(id);
if (obj.event === 'clearFilter') {
// 清除所有筛选条件并重载表格
// 参数: tableId
soulTable.clearFilter('myTable')
}else if(obj.event === 'getData'){
var getData = table.getData(id);
console.log(getData);
layer.alert(layui.util.escape(JSON.stringify(getData)));
}
});
//触发单元格工具事件
table.on('tool(bar)', function(obj) { // 双击 toolDouble
console.log(obj);
if(obj.event === 'del'){
alert('删除...')
}
});
// }, null, 'define');
});
</script>
</body>
</html>
\ No newline at end of file
......@@ -35,6 +35,9 @@
<button class="layui-btn layui-btn-sm layui-btn-primary" lay-event="default-row">
单行
</button>
<button class="layui-btn layui-btn-sm layui-btn-primary" lay-event="jxs">
解析管理
</button>
</div>
</script>
......@@ -383,6 +386,9 @@ layui.use(['table', 'dropdown'], function(){
});
layer.msg('已设为单行');
break;
case 'jxs':
location.href = 'jxs';
break;
case 'LAYTABLE_TIPS':
layer.alert('Table for layui-v'+ layui.v);
break;
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册