Commit b7cff4a0 by 杨树贤

供应商入驻跟进

parent 2fb2c330
......@@ -39,4 +39,25 @@ class ChainApiController extends Controller
$chain = ChainModel::where('chain_id', $chainId)->first()->toArray();
$this->response(0, 'ok', $chain);
}
//跟进
public function checkChain($request)
{
$map = $request->only([
'status',
'check_content',
'chain_id',
]);
if (empty($map['check_content']) && $map['status'] == 3) {
$this->response(-1, '跟进内容不能为空');
}
if (empty($map['status'])) {
$this->response(-1, '跟进结果不能为空');
}
$result = (new ChainService())->checkChain($map);
if (!$result) {
$this->response(0, '跟进出错,请联系管理员');
}
$this->response(0, '跟进成功');
}
}
......@@ -46,4 +46,11 @@ class ChainController extends Controller
$this->data['view'] = 'ChainList';
return $this->view('供应商申请列表');
}
}
\ No newline at end of file
public function CheckChain($request)
{
$this->data['title'] = '供应商入驻跟进';
$this->data['view'] = 'CheckChain';
return $this->view('供应商入驻跟进');
}
}
......@@ -10,10 +10,8 @@ use App\Model\SupplierChannelModel;
class ChainFilter
{
//查询条件
public function listFilter($map)
public function listFilter($query, $map)
{
$model = new ChainModel();
$query = $model->orderBy('chain_id', 'desc');
if (!empty($map['com_name'])) {
$query->where('com_name', 'like', "%${map['com_name']}%");
......@@ -32,6 +30,22 @@ class ChainFilter
if (!empty($map['supplier_type'])) {
$query->where('supplier_type', $map['supplier_type']);
}
if (!empty($map['check_status'])) {
$query->where('check_status', $map['check_status']);
}
if ((isset($map['is_entity']) && $map['is_entity'] === '0') || !empty($map['is_entity'])) {
$query->where('is_entity', $map['is_entity']);
}
if (!empty($map['has_supplier'])) {
$supplierNames = SupplierChannelModel::where('is_type', 0)->pluck('supplier_name')->toArray();
if ($map['has_supplier'] == 1) {
$query->whereIn('com_name', $supplierNames);
} else {
$query->whereNotIn('com_name', $supplierNames);
}
}
if (!empty($map['create_time'])) {
$times = explode('~', $map['create_time']);
......@@ -42,4 +56,4 @@ class ChainFilter
return $query;
}
}
\ No newline at end of file
}
......@@ -6,6 +6,8 @@ namespace App\Http\Services;
//后台用户相关信息服务
use App\Http\Controllers\Filter\ChainFilter;
use App\Http\Transformers\ChainTransformer;
use App\Model\ChainCheckModel;
use App\Model\ChainModel;
class ChainService
{
......@@ -14,11 +16,37 @@ class ChainService
public function getChainList($map)
{
$limit = array_get($map, 'limit', 10);
$model = new ChainModel();
$query = $model->with(['chain_check', 'supplier' => function ($q) {
$q->select(['supplier_name', 'supplier_id']);
}])->orderBy('chain_id', 'desc');
$filter = new ChainFilter();
$query = $filter->listFilter($map);
$query = $filter->listFilter($query, $map);
$list = $query->paginate($limit)->toArray();
$transformer = new ChainTransformer();
$list['data'] = $transformer->transformList($list['data']);
return $list;
}
}
\ No newline at end of file
//跟进
public function checkChain($map)
{
$data = [
'chain_id' => $map['chain_id'],
'check_status' => $map['status'],
'check_name' => request()->user->name,
'check_time' => time(),
'check_uid' => request()->user->userId,
'check_content' => $map['check_content']
];
$result = ChainCheckModel::insert($data);
if ($result) {
ChainModel::where('chain_id', $map['chain_id'])->update([
'check_status' => $map['status'],
]);
}
return $result;
}
}
......@@ -19,6 +19,8 @@ class ChainTransformer
$item['data_type_name'] = array_get(config('field.ChainDataType'), $item['data_type'], '无');
$item['company_nature'] = array_get(config('field.ChainCompanyNature'), $item['company_nature'], '无');
$item['region'] = array_get(config('field.ChainRegion'), $item['region'], '无');
$item['check_status_name'] = array_get(config('field.ChainCheckStatus'),$item['check_status']);
$item['is_entity_name'] = array_get(config('field.IsEntity'),$item['is_entity']);
if (!empty($item['mobile'])) {
$item['mobile'] = substr($item['mobile'], 0, 3) . '****' . substr($item['mobile'], 7);
}
......@@ -33,6 +35,14 @@ class ChainTransformer
$item['email'] = $emailTemp;
}
}
if (!empty($item['chain_check'])) {
foreach ($item['chain_check'] as &$value) {
$value['check_status_name'] = array_get(config('field.ChainCheckStatus'),$value['check_status']);
}
unset($value);
}
$item['sub'] = $item['chain_check'];
}
unset($item);
......
<?php
namespace App\Model;
use App\Http\Services\AdminUserService;
use App\Http\Services\DepartmentService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;
class ChainCheckModel extends Model
{
protected $connection = 'liexin';
protected $table = 'chain_check';
protected $primaryKey = 'id';
public $timestamps = false;
}
......@@ -13,4 +13,14 @@ class ChainModel extends Model
protected $table = 'chain';
protected $primaryKey = 'chain_id';
public $timestamps = false;
public function chain_check()
{
return $this->hasMany(ChainCheckModel::class, 'chain_id', 'chain_id');
}
public function supplier()
{
return $this->hasOne(SupplierChannelModel::class, 'supplier_name', 'com_name');
}
}
......@@ -312,5 +312,13 @@ return [
0 => '待确认',
1 => '是',
-2 => '驳回'
],
'ChainCheckStatus' => [
0 => '待跟进',
1 => '渠道已跟进',
2 => '采购已通过',
3 => '采购未通过',
4 => '采购未反馈',
]
];
/**
*
* @name: 表格增强插件
* @author: yelog
* @link: https://github.com/yelog/layui-soul-table
* @license: MIT
* @version: v1.6.2
*/
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()
if (newIndex !== index) { // 有位置变动
var cache = table.cache[tableId],
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.2
*/
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()
if (newIndex !== index) { // 有位置变动
var cache = table.cache[tableId],
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.2
*/
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()
if (newIndex !== index) { // 有位置变动
var cache = table.cache[tableId],
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.2
*/
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()
if (newIndex !== index) { // 有位置变动
var cache = table.cache[tableId],
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.2
*/
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);
});
This diff could not be displayed because it is too large.
/**
*
* @name: 子表格扩展
* @author: yelog
* @link: https://github.com/yelog/layui-soul-table
* @license: MIT
* @version: v1.6.2
*/
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);
});
/** 表格扩展模块 date:2020-02-29 License By http://easyweb.vip */
layui.define(["layer","table","laytpl","contextMenu"],function(f){var g=layui.jquery;var i=layui.layer;var q=layui.table;var n=layui.laytpl;var e=layui.contextMenu;var c=layui.device();var h="tb-search";var p="tb-refresh";var b="tb-export";var m="txField_";var a={};a.merges=function(w,y,s,v){if(typeof s==="boolean"){v=s;s=undefined}var r=g('[lay-filter="'+w+'"]+.layui-table-view>.layui-table-box>.layui-table-body>table');var t=r.find(">tbody>tr");for(var u=0;u<y.length;u++){if(s){x(w,y[u],s[u])}else{x(w,y[u])}}t.find('[del="true"]').remove();if(v===undefined||v){q.on("sort("+w+")",function(){a.merges(w,y,s,false)})}function x(z,F,G){var D=q.cache[z];if(D.length>0){var H,A=1;if(G){H=D[0][G]}else{H=t.eq(0).find("td").eq(F).find(".layui-table-cell").html()}for(var E=1;E<D.length;E++){var I;if(G){I=D[E][G]}else{I=t.eq(E).find("td").eq(F).find(".layui-table-cell").html()}if(I===H){A++;if(E===D.length-1){t.eq(E-A+1).find("td").eq(F).attr("rowspan",A);for(var C=1;C<A;C++){t.eq(E-C+1).find("td").eq(F).attr("del","true")}}}else{t.eq(E-A).find("td").eq(F).attr("rowspan",A);for(var B=1;B<A;B++){t.eq(E-B).find("td").eq(F).attr("del","true")}A=1;H=I}}}}};a.bindCtxMenu=function(t,r){var u=q.cache[t];var s="#"+t+"+.layui-table-view .layui-table-body tr";g(s).bind("contextmenu",function(w){var x=g(this);g(s).removeClass("layui-table-click");x.addClass("layui-table-click");var v;if(typeof r==="function"){v=r(u[x.data("index")],w.currentTarget)}else{v=r}function y(B){if(!B){return}var z=[];for(var A=0;A<B.length;A++){z.push({icon:B[A].icon,name:B[A].name,_click:B[A].click,click:function(E,D){var C=g(D.currentTarget);this._click&&this._click(u[C.data("index")],D.currentTarget);C.removeClass("layui-table-click")},subs:y(B[A].subs)})}return z}e.show(y(v),w.clientX,w.clientY,w);return false})};a.exportData=function(v){var w=v.cols;var J=v.data;var H=v.fileName;var r=v.expType;var y=v.option;y||(y={});if(c.ie){return i.msg("不支持ie导出")}if(typeof J==="string"){var G=i.load(2);y.url=J;a.loadUrl(y,function(L){i.close(G);v.data=L;a.exportData(v)});return}for(var F=0;F<w.length;F++){for(var E=0;E<w[F].length;E++){if(w[F][E].type===undefined){w[F][E].type="normal"}if(w[F][E].hide===undefined){w[F][E].hide=false}}}var K=[],A=[],z=[];q.eachCols(undefined,function(L,M){if(M.type==="normal"&&!M.hide){K.push(M.title||"");A.push(M.field||(m+L))}},w);var I=a.parseTbData(w,a.deepClone(J),true);for(var B=0;B<I.length;B++){var u=[];for(var C=0;C<A.length;C++){var x=I[B][A[C]];x&&(x=x.toString().replace(/,/g,","));u.push(x)}z.push(u.join(","))}var t=document.createElement("a");var s=({csv:"text/csv",xls:"application/vnd.ms-excel"})[r||"xls"];var D=encodeURIComponent(K.join(",")+"\r\n"+z.join("\r\n"));t.href="data:"+s+";charset=utf-8,\ufeff"+D;t.download=(H||"table")+"."+(r||"xls");document.body.appendChild(t);t.click();document.body.removeChild(t)};a.exportDataX=function(r){layui.use("excel",function(){var A=layui.excel;var D=r.cols;var v=r.data;var t=r.fileName;var E=r.expType;var x=r.option;x||(x={});E||(E="xlsx");if(v&&typeof v==="string"){var u=i.load(2);x.url=v;a.loadUrl(x,function(F){i.close(u);r.data=F;a.exportDataX(r)});return}for(var w=0;w<D.length;w++){for(var s=0;s<D[w].length;s++){if(D[w][s].type===undefined){D[w][s].type="normal"}if(D[w][s].hide===undefined){D[w][s].hide=false}}}var z={},y=[];q.eachCols(undefined,function(F,G){if(G.type==="normal"&&!G.hide){var H=G.field||(m+F);y.push(H);z[H]=G.title||""}},D);var B=a.parseTbData(D,a.deepClone(v),true);var C=A.filterExportData(B,y);C.unshift(z);A.exportExcel({sheet1:C},(t||"table")+"."+E,E)})};a.exportDataBack=function(t,x,r){x||(x={});if(!r||r.toString().toLowerCase()==="get"){var v="";for(var z in x){if(!v){v=("?"+z+"="+x[z])}else{v+=("&"+z+"="+x[z])}}window.open(t+v)}else{var s='<html><body><form id="eFrom" action="'+t+'" method="'+r+'">';for(var w in x){s+=('<textarea name="'+w+'">'+x[w]+"</textarea>")}s+="</form></body></html>";g("#exportFrame").remove();g("body").append('<iframe id="exportFrame" style="display: none;"></iframe>');var A=document.getElementById("exportFrame");var y=A.contentWindow;var u=y.document;y.focus();u.open();u.write(s);u.close();u.getElementById("eFrom").submit()}};a.render=function(t){var r=g(t.elem).attr("lay-filter");t.autoSort=false;var s=q.render(t);q.on("sort("+r+")",function(w){var u=w.field,x=w.type;var v=g.extend(t.where,{sort:u,order:x});s.reload({where:v,page:{curr:1}})});return s};a.renderFront=function(w){var v,t=g(w.elem).attr("lay-filter");w.autoSort=false;for(var s=0;s<w.cols.length;s++){for(var r=0;r<w.cols[s].length;r++){if(w.cols[s][r].templet&&!w.cols[s][r].field){w.cols[s][r].field=m+s+"_"+r}}}if(w.url){var u=a.deepClone(w);u.data=[];u.url=undefined;v=q.render(u);v.reloadUrl=function(y){var x=a.deepClone(w);y&&(x=g.extend(x,y));g(w.elem+"+.layui-table-view>.layui-table-box").append('<div class="layui-table-init"><i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i></div>');a.loadUrl(x,function(z){v.reload({url:"",data:z,page:{curr:1}});a.putTbData(t,a.parseTbData(x.cols,z));g("input["+h+'="'+t+'"]').val("");window.tbX.cacheSearch[t]=undefined})};v.reloadUrl()}else{v=q.render(w);v.reloadData=function(x){v.reload(x);a.parseTbData(w.cols,x.data);a.putTbData(t,x.data);g("input["+h+'="'+t+'"]').val("");window.tbX.cacheSearch[t]=undefined};a.putTbData(t,a.parseTbData(w.cols,w.data))}a.renderAllTool(v);return v};a.loadUrl=function(t,u){t.response=g.extend({statusName:"code",statusCode:0,msgName:"msg",dataName:"data",countName:"count"},t.response);var r=t.response;var s=t.where;if(t.contentType&&t.contentType.indexOf("application/json")===0){s=JSON.stringify(s)}g.ajax({type:t.method||"get",url:t.url,contentType:t.contentType,data:s,dataType:"json",headers:t.headers||{},success:function(v){if(typeof t.parseData==="function"){v=t.parseData(v)||v}if(v[r.statusName]!=r.statusCode){var w=v[r.msgName]||("返回的数据不符合规范,正确的成功状态码 ("+r.statusName+") 应为:"+r.statusCode);i.msg(w,{icon:2})}else{u(v[r.dataName])}},error:function(w,v){i.msg("数据接口请求异常:"+v,{icon:2})}})};a.parseTbData=function(x,u,s){var w=[];q.eachCols(undefined,function(A,B){if(B.templet){var z={field:((B.field&&(s||B.field.indexOf(m)===0))?B.field:("txField_"+A))};if(typeof B.templet==="string"){z.templet=function(D){var C=undefined;n(g(B.templet).html()).render(D,function(E){C=E});return C}}else{z.templet=B.templet}w.push(z)}},x);for(var t=0;t<u.length;t++){var v=u[t];for(var r=0;r<w.length;r++){var y="<div>"+w[r].templet(v)+"</div>";v[w[r].field]=g(y).not(".export-hide").text().replace(/(^\s*)|(\s*$)/g,"")}}return u};a.putTbData=function(s,r){window.tbX.cache[s]=r};a.getTbData=function(s){var r=window.tbX.cache[s];return a.deepClone(r||q.cache[s])};a.filterData=function(z,s,r){var t=[],x;for(var w=0;w<z.length;w++){var v=z[w];if(!x){if(!s){x=[];for(var y in v){if(!v.hasOwnProperty(y)){continue}x.push(y)}}else{x=s.split(",")}}for(var u=0;u<x.length;u++){if(a.isContains(v[x[u]],r)){t.push(v);break}}}return t};a.isContains=function(s,r){s||(s="");r||(r="");s=s.toString().toLowerCase();r=r.toString().toLowerCase();if(s===r||s.indexOf(r)>=0){return true}return false};a.renderAllTool=function(r){o(r);l(r);j(r);k(r)};a.deepClone=function(u){var r;var s=a.isClass(u);if(s==="Object"){r={}}else{if(s==="Array"){r=[]}else{return u}}for(var t in u){if(!u.hasOwnProperty(t)){continue}var v=u[t];if(a.isClass(v)==="Object"){r[t]=arguments.callee(v)}else{if(a.isClass(v)==="Array"){r[t]=arguments.callee(v)}else{r[t]=u[t]}}}return r};a.isClass=function(r){if(r===null){return"Null"}if(r===undefined){return"Undefined"}return Object.prototype.toString.call(r).slice(8,-1)};window.tbX||(window.tbX={});window.tbX.cache||(window.tbX.cache={});window.tbX.cacheSearch||(window.tbX.cacheSearch={});var j=function(s){var r=s.config.id,t=g("input["+h+'="'+r+'"]');if(!(t&&t.length>0)){return}if(!t.attr("placeholder")){t.attr("placeholder","输入关键字按回车键搜索")}t.off("keydown").on("keydown",function(x){if(x.keyCode!==13){return}var u=t.attr("name");var y=t.val().replace(/(^\s*)|(\s*$)/g,"");var v=i.msg("搜索中..",{icon:16,shade:0.01,time:0});var w=a.getTbData(r);var z=a.filterData(w,u,y);window.tbX.cacheSearch[r]=z;s.reload({url:"",data:z,page:{curr:1}});i.close(v)})};var l=function(s){var r=s.config.id;q.on("sort("+r+")",function(w){var t=w.field,x=w.type;var u=i.msg("加载中..",{icon:16,shade:0.01,time:0});var v=window.tbX.cacheSearch[r];v||(v=a.getTbData(r));if(x){v=v.sort(function(B,z){var A=B[t],y=z[t];if(x==="asc"){return(A===y)?0:((A<y)?-1:1)}else{return(A===y)?0:((A<y)?1:-1)}})}s.reload({initSort:w,url:"",data:v,page:{curr:1}});i.close(u)})};var o=function(r){g("["+p+'="'+r.config.id+'"]').off("click").on("click",function(){if(r.reloadUrl){r.reloadUrl()}else{r.reload({page:{curr:1}})}})};var k=function(s){var r=s.config.id;g("["+b+'="'+r+'"]').off("click").on("click",function(t){if(g(this).find(".tbx-dropdown-menu").length>0){return}if(t!==void 0){t.preventDefault();t.stopPropagation()}var u='<div class="tbx-dropdown-menu">';u+=' <div class="tbx-dropdown-menu-item" data-type="check">导出选中数据</div>';u+=' <div class="tbx-dropdown-menu-item" data-type="current">导出当前页数据</div>';u+=' <div class="tbx-dropdown-menu-item" data-type="all">导出全部数据</div>';u+=" </div>";g(this).append(u);g(this).addClass("tbx-dropdown-btn");g(this).parent().css("position","relative");g(this).parent().css("z-index","9998");g(".tbx-dropdown-menu").off("click").on("click",".tbx-dropdown-menu-item",function(x){var w=g(this).data("type");if(w==="check"){var v=q.checkStatus(r);if(v.data.length===0){i.msg("请选择要导出的数据",{icon:2})}else{g(".tbx-dropdown-menu").remove();a.exportData({fileName:s.config.title,cols:s.config.cols,data:v.data})}}else{if(w==="current"){a.exportData({fileName:s.config.title,cols:s.config.cols,data:q.cache[r]})}else{if(w==="all"){a.exportData({fileName:s.config.title,cols:s.config.cols,data:a.getTbData(r)})}}}if(x!==void 0){x.preventDefault();x.stopPropagation()}})});g(document).off("click.tbxDropHide").on("click.tbxDropHide",function(){g(".tbx-dropdown-menu").remove()})};var d=function(){var r=".tbx-dropdown-btn {";r+=" position: relative;";r+=" }";r+=" .tbx-dropdown-btn:hover {";r+=" opacity: 1";r+=" }";r+=" .tbx-dropdown-menu {";r+=" position: absolute;";r+=" top: 100%;";r+=" right: 0;";r+=" padding: 5px 0;";r+=" margin: 5px 0 0 0;";r+=" overflow: visible;";r+=" min-width: 110px;";r+=" background: #fff;";r+=" border-radius: 2px;";r+=" box-shadow: 0 2px 4px rgba(0, 0, 0, .12);";r+=" border: 1px solid #d2d2d2;";r+=" z-index: 9998;";r+=" cursor: default;";r+=" }";r+=" .tbx-dropdown-menu .tbx-dropdown-menu-item {";r+=" display: block;";r+=" color: #555;";r+=" font-size: 14px;";r+=" padding: 10px 15px;";r+=" text-decoration: none;";r+=" white-space: nowrap;";r+=" cursor: pointer;";r+=" user-select: none;";r+=" line-height: normal;";r+=" }";r+=" .tbx-dropdown-menu .tbx-dropdown-menu-item:hover {";r+=" background-color: #eeeeee;";r+=" }";r+=" .export-show {";r+=" display: none;";r+=" }";return r};g("head").append('<style id="ew-css-tbx" type="text/css">'+d()+"</style>");f("tableX",a)});
\ No newline at end of file
/** 树形表格3.x Created by wangfan on 2020-04-06 https://gitee.com/whvse/treetable-lay */
layui.define(["laytpl","form","util"],function(s){var g=layui.jquery;var d=layui.laytpl;var c=layui.form;var b=layui.util;var o=layui.device();var h="treeTable";var k={};var e={elem:undefined,cols:undefined,url:undefined,method:undefined,where:undefined,contentType:undefined,headers:undefined,parseData:undefined,request:{pidName:"pid"},toolbar:undefined,defaultToolbar:["filter","exports","print"],width:undefined,height:undefined,cellMinWidth:90,done:undefined,data:undefined,title:undefined,skin:undefined,even:undefined,size:undefined,text:{none:"无数据"},reqData:undefined,useAdmin:false,tree:{idName:"id",pidName:"pid",childName:"children",haveChildName:"haveChild",openName:"open",iconIndex:0,arrowType:undefined,onlyIconControl:undefined,getIcon:function(u){var t=u[this.haveChildName];if(t!==undefined){t=t===true||t==="true"}else{if(u[this.childName]){t=u[this.childName].length>0}}if(t){return'<i class="ew-tree-icon layui-icon layui-icon-layer"></i>'}else{return'<i class="ew-tree-icon layui-icon layui-icon-file"></i>'}}}};var r={field:undefined,title:undefined,width:undefined,minWidth:undefined,type:"normal",fixed:undefined,hide:undefined,unresize:undefined,style:undefined,align:undefined,colspan:undefined,rowspan:undefined,templet:undefined,toolbar:undefined,"class":undefined,singleLine:undefined};var p=function(t){k[t.elem.substring(1)]=this;this.reload(t)};p.prototype.initOptions=function(t){var D=this;function B(J){if(!J.INIT_OK){J=g.extend({INIT_OK:true},r,J)}if(J.type==="space"){if(!J.width){J.width=15}J.minWidth=J.width}else{if(J.type==="numbers"){if(!J.width){J.width=40}J.minWidth=J.width;if(!J.singleLine){J.singleLine=false}if(!J.unresize){J.unresize=true}if(!J.align){J.align="center"}}else{if(J.type==="checkbox"||J.type==="radio"){if(!J.width){J.width=48}J.minWidth=J.width;if(!J.singleLine){J.singleLine=false}if(!J.unresize){J.unresize=true}if(!J.align){J.align="center"}}}}if(J.toolbar){J.type="tool"}return J}if("Array"!==l(t.cols[0])){t.cols=[t.cols]}for(var w=0;w<t.cols.length;w++){for(var u=0;u<t.cols[w].length;u++){t.cols[w][u].INIT_OK=undefined;t.cols[w][u].key=undefined;t.cols[w][u].colGroup=undefined;t.cols[w][u].HAS_PARENT=undefined;t.cols[w][u].parentKey=undefined;t.cols[w][u].PARENT_COL_INDEX=undefined}}var F=[],G=0;for(var y=0;y<t.cols.length;y++){var C=t.cols[y];for(var x=0;x<C.length;x++){var A=C[x];if(!A){C.splice(x,1);continue}A=B(A);A.key=y+"-"+x;var I=undefined;if(A.colGroup||A.colspan>1){A.colGroup=true;A.type="group";I=[];G++;var z=0;for(var v=0;v<t.cols[y+1].length;v++){var H=g.extend({INIT_OK:true},r,t.cols[y+1][v]);if(H.HAS_PARENT||(z>1&&z==A.colspan)){t.cols[y+1][v]=H;continue}H.HAS_PARENT=true;H.parentKey=y+"-"+x;H.key=(y+1)+"-"+v;H.PARENT_COL_INDEX=G;H=B(H);I.push(H);z=z+parseInt(H.colspan>1?H.colspan:1);t.cols[y+1][v]=H}}A.CHILD_COLS=I;if(!A.PARENT_COL_INDEX){F.push(A)}t.cols[y][x]=A}}this.options=g.extend(true,{},e,t);this.options.colArrays=F;if(this.options.url){this.options.reqData=function(J,K){if(!D.options.where){D.options.where={}}if(J){D.options.where[D.options.request.pidName]=J[D.options.tree.idName]}(D.options.useAdmin?layui.admin:g).ajax({url:D.options.url,data:D.options.contentType&&D.options.contentType.indexOf("application/json")===0?JSON.stringify(D.options.where):D.options.where,headers:D.options.headers,type:D.options.method,dataType:"json",contentType:D.options.contentType,success:function(L){if(D.options.parseData){L=D.options.parseData(L)}if(L.code==0){K(L.data)}else{K(L.msg||"加载失败")}},error:function(L){K(L.status+" - "+L.statusText)}})}}else{if(this.options.data&&this.options.data.length>0&&this.options.tree.isPidData){this.options.data=a.pidToChildren(this.options.data,this.options.tree.idName,this.options.tree.pidName,this.options.tree.childName)}}if("default"===this.options.toolbar){this.options.toolbar=["<div>",' <div class="ew-tree-table-tool-item" title="添加" lay-event="add">',' <i class="layui-icon layui-icon-add-1"></i>'," </div>",' <div class="ew-tree-table-tool-item" title="修改" lay-event="update">',' <i class="layui-icon layui-icon-edit"></i>'," </div>",' <div class="ew-tree-table-tool-item" title="删除" lay-event="delete">',' <i class="layui-icon layui-icon-delete"></i>'," </div>","</div>"].join("")}if(typeof this.options.tree.getIcon==="string"){var E=this.options.tree.getIcon;this.options.tree.getIcon=function(K){if(E!=="ew-tree-icon-style2"){return E}var J=K[this.haveChildName];if(J!==undefined){J=J===true||J==="true"}else{if(K[this.childName]){J=K[this.childName].length>0}}if(J){return'<i class="ew-tree-icon ew-tree-icon-folder"></i>'}else{return'<i class="ew-tree-icon ew-tree-icon-file"></i>'}}}};p.prototype.init=function(){var E=this.options;var u=g(E.elem);var B=E.elem.substring(1);u.removeAttr("lay-filter");if(u.next(".ew-tree-table").length===0){u.css("display","none");u.after(['<div class="layui-form ew-tree-table" lay-filter="',B,'" style="',E.style||"",'">',' <div class="ew-tree-table-tool" style="display: none;"></div>',' <div class="ew-tree-table-head">',' <table class="layui-table"></table>'," </div>",' <div class="ew-tree-table-box">',' <table class="layui-table"></table>',' <div class="ew-tree-table-loading">',' <i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i>'," </div>",' <div class="ew-tree-table-empty">',E.text.none||"","</div>"," </div>","</div>"].join(""))}var A=this.getComponents();if(E.skin){A.$table.attr("lay-skin",E.skin)}if(E.size){A.$table.attr("lay-size",E.size)}if(E.even){A.$table.attr("lay-even",E.even)}A.$toolbar.empty();if(E.toolbar===false||E.toolbar===undefined){A.$toolbar.hide()}else{A.$toolbar.show();if(typeof E.toolbar==="string"){d(g(E.toolbar).html()).render({},function(F){A.$toolbar.html(F)})}var C=['<div class="ew-tree-table-tool-right">'];for(var y=0;y<E.defaultToolbar.length;y++){var w;if("filter"===E.defaultToolbar[y]){w={title:"筛选",layEvent:"LAYTABLE_COLS",icon:"layui-icon-cols"}}else{if("exports"===E.defaultToolbar[y]){w={title:"导出",layEvent:"LAYTABLE_EXPORT",icon:"layui-icon-export"}}else{if("print"===E.defaultToolbar[y]){w={title:"打印",layEvent:"LAYTABLE_PRINT",icon:"layui-icon-print"}}else{w=E.defaultToolbar[y]}}}C.push('<div class="ew-tree-table-tool-item"');C.push(' title="'+w.title+'"');C.push(' lay-event="'+w.layEvent+'">');C.push('<i class="layui-icon '+w.icon+'"></i></div>')}A.$toolbar.append(C.join("")+"</div>")}if(E.width){A.$view.css("width",E.width);A.$tHeadGroup.css("width",E.width);A.$tBodyGroup.css("width",E.width)}var v=this.resize(true);var D="<thead>"+this.renderBodyTh()+"</thead>";A.$tBodyGroup.children("style").remove();if(E.height){A.$tHead.html(v+D);A.$tBody.html(v+"<tbody></tbody>");if(E.height.indexOf("full-")===0){var z=parseFloat(E.height.substring(5))+A.$toolbar.outerHeight()+A.$tHeadGroup.outerHeight()+1;A.$tBodyGroup.append(['<style>[lay-filter="',B,'"] .ew-tree-table-box {'," height: ",m()-z,"px;"," height: -moz-calc(100vh - ",z,"px);"," height: -webkit-calc(100vh - ",z,"px);"," height: calc(100vh - ",z,"px);","}</style>"].join(""));A.$tBodyGroup.data("full",z);A.$tBodyGroup.css("height","")}else{A.$tBodyGroup.css("height",E.height);A.$tBodyGroup.data("full","")}A.$tHeadGroup.show()}else{A.$tHeadGroup.hide();var x={lg:50,sm:30,md:38};A.$tBodyGroup.append(['<style>[lay-filter="',B,'"] .ew-tree-table-box:before {',' content: "";'," position: absolute;"," top: 0; left: 0; right: 0;"," height: "+(x[E.size||"md"]*E.cols.length)+"px;"," background-color: #f2f2f2;"," border-bottom: 1px solid #e6e6e6;","}</style>"].join(""));A.$tBody.html(v+D+"<tbody></tbody>")}c.render("checkbox",B);function t(H){var F=H.data("parent"),G;if(!F){return}var I=A.$table.children("thead").children("tr").children('[data-key="'+F+'"]');var J=I.attr("colspan")-1;I.attr("colspan",J);if(J===0){I.addClass("layui-hide")}t(I)}A.$table.children("thead").children("tr").children("th.layui-hide").each(function(){t(g(this))});if(E.reqData){this.options.data=undefined;this.renderBodyAsync()}else{if(E.data&&E.data.length>0){this.renderBodyData(E.data)}else{A.$loading.hide();A.$empty.show()}}};p.prototype.bindEvents=function(){var v=this;var t=this.options;var u=this.getComponents();var w=u.$table.children("tbody");var x=function(y){var z=g(this);if(!z.is("tr")){var C=z.parent("tr");if(C.length>0){z=C}else{z=z.parentsUntil("tr").last().parent()}}var A=v.getDataByTr(z);var B={tr:z,data:A,del:function(){var F=z.data("index");var D=parseInt(z.data("indent"));z.nextAll("tr").each(function(){if(parseInt(g(this).data("indent"))<=D){return false}g(this).remove()});var G=(typeof F==="number"?1:F.split("-").length);z.nextAll("tr").each(function(){var H=g(this);if(parseInt(H.data("indent"))<D){return false}var I=H.data("index").toString().split("-");I[G-1]=parseInt(I[G-1])-1;H.data("index",I.join("-"))});var E=z.prevAll("tr");v.del(undefined,F);z.remove();v.renderNumberCol();E.each(function(){var H=parseInt(g(this).data("indent"));if(H>=D){return true}v.checkParentCB(g(this));D=H});v.checkChooseAllCB();if(t.data.length===0){u.$empty.show()}f(u.$view)},update:function(E){A=g.extend(true,A,E);var D=parseInt(z.data("indent"));v.renderBodyTr(A,D,undefined,z);c.render(null,u.filter);v.renderNumberCol();z.prevAll("tr").each(function(){var F=parseInt(g(this).data("indent"));if(F>=D){return true}v.checkParentCB(g(this));D=F});v.checkChooseAllCB()}};return g.extend(B,y)};w.off("click.fold").on("click.fold",".ew-tree-pack",function(C){layui.stope(C);var A=g(this).parentsUntil("tr").last().parent();if(A.hasClass("ew-tree-table-loading")){return}var y=A.data("have-child");if(y!==true&&y!=="true"){return}var z=A.hasClass("ew-tree-table-open");var B=v.getDataByTr(A);if(!z&&!B[t.tree.childName]){v.renderBodyAsync(B,A)}else{B[t.tree.openName]=i(A)}});w.off("click.tool").on("click.tool","*[lay-event]",function(z){layui.stope(z);var y=g(this);layui.event.call(this,h,"tool("+u.filter+")",x.call(this,{event:y.attr("lay-event")}))});c.on("radio("+u.radioFilter+")",function(y){var z=v.getDataByTr(g(y.elem).parentsUntil("tr").last().parent());v.removeAllChecked();z.LAY_CHECKED=true;z.LAY_INDETERMINATE=false;layui.event.call(this,h,"checkbox("+u.filter+")",{checked:true,data:z,type:"one"})});c.on("checkbox("+u.checkboxFilter+")",function(C){var B=C.elem.checked;var E=g(C.elem);var z=E.next(".layui-form-checkbox");if(!B&&E.hasClass("ew-form-indeterminate")){B=true;E.prop("checked",B);z.addClass("layui-form-checked");E.removeClass("ew-form-indeterminate")}var A=E.parentsUntil("tr").last().parent();var D=v.getDataByTr(A);D.LAY_CHECKED=B;D.LAY_INDETERMINATE=false;if(D[t.tree.childName]&&D[t.tree.childName].length>0){v.checkSubCB(A,B)}var y=parseInt(A.data("indent"));A.prevAll("tr").each(function(){var F=parseInt(g(this).data("indent"));if(F<y){v.checkParentCB(g(this));y=F}});v.checkChooseAllCB();layui.event.call(this,h,"checkbox("+u.filter+")",{checked:B,data:D,type:"more"})});c.on("checkbox("+u.chooseAllFilter+")",function(A){var z=A.elem.checked;var B=g(A.elem);var y=B.next(".layui-form-checkbox");if(!t.data||t.data.length===0){B.prop("checked",false);y.removeClass("layui-form-checked");B.removeClass("ew-form-indeterminate");return}if(!z&&B.hasClass("ew-form-indeterminate")){z=true;B.prop("checked",z);y.addClass("layui-form-checked");B.removeClass("ew-form-indeterminate")}layui.event.call(this,h,"checkbox("+u.filter+")",{checked:z,type:"all"});v.checkSubCB(u.$tBody.children("tbody"),z)});w.off("click.row").on("click.row","tr",function(){layui.event.call(this,h,"row("+u.filter+")",x.call(this,{}))});w.off("dblclick.rowDouble").on("dblclick.rowDouble","tr",function(){layui.event.call(this,h,"rowDouble("+u.filter+")",x.call(this,{}))});w.off("click.cell").on("click.cell","td",function(C){var y=g(this);var E=y.data("type");if(E==="checkbox"||E==="radio"){return layui.stope(C)}var H=y.data("edit");var G=y.data("field");if(H){layui.stope(C);if(w.find(".ew-tree-table-edit").length>0){return}var B=y.data("index");var z=y.find(".ew-tree-table-indent").length;var D=v.getDataByTr(y.parent());if("text"===H||"number"===H){var F=g('<input type="'+H+'" class="layui-input ew-tree-table-edit"/>');F[0].value=D[G];y.append(F);F.focus();F.blur(function(){var K=g(this).val();if(K==D[G]){return g(this).remove()}var I=layui.event.call(this,h,"edit("+u.filter+")",x.call(this,{value:K,field:G}));if(I===false){g(this).addClass("layui-form-danger");g(this).focus()}else{D[G]=K;var J=y.data("key").split("-");v.renderBodyTd(D,z,B,y,t.cols[J[0]][J[1]])}})}else{console.error("不支持的单元格编辑类型:"+H)}}else{var A=layui.event.call(this,h,"cell("+u.filter+")",x.call(this,{td:y,field:G}));if(A===false){layui.stope(C)}}});w.off("dblclick.cellDouble").on("dblclick.cellDouble","td",function(C){var D=g(this);var z=D.data("type");if(z==="checkbox"||z==="radio"){return layui.stope(C)}var A=D.data("edit");var B=D.data("field");if(A){return layui.stope(C)}var y=layui.event.call(this,h,"cellDouble("+u.filter+")",x.call(this,{td:D,field:B}));if(y===false){layui.stope(C)}});u.$toolbar.off("click.toolbar").on("click.toolbar","*[lay-event]",function(A){layui.stope(A);var z=g(this);var y=z.attr("lay-event");if("LAYTABLE_COLS"===y){v.toggleCol()}else{if("LAYTABLE_EXPORT"===y){v.exportData("show")}else{if("LAYTABLE_PRINT"===y){v.printTable()}else{layui.event.call(this,h,"toolbar("+u.filter+")",{event:y,elem:z})}}}});u.$tBodyGroup.on("scroll",function(){var y=g(this);u.$tHeadGroup.scrollLeft(y.scrollLeft())});u.$toolbar.off("click.export").on("click.export",".layui-table-tool-panel>[data-type]",function(){var y=g(this).data("type");if("csv"===y||"xls"===y){v.exportData(y)}});u.$toolbar.off("click.panel").on("click.panel",".layui-table-tool-panel",function(y){layui.stope(y)});c.on("checkbox("+u.colsToggleFilter+")",function(y){v.toggleCol(y.elem.checked,undefined,y.value)})};p.prototype.getComponents=function(){var v=g(this.options.elem).next(".ew-tree-table");var t=v.attr("lay-filter");var w=v.children(".ew-tree-table-head");var u=v.children(".ew-tree-table-box");return{$view:v,filter:t,$tHeadGroup:w,$tBodyGroup:u,$tHead:w.children(".layui-table"),$tBody:u.children(".layui-table"),$table:v.find(".layui-table"),$toolbar:v.children(".ew-tree-table-tool"),$empty:u.children(".ew-tree-table-empty"),$loading:u.children(".ew-tree-table-loading"),checkboxFilter:"ew_tb_checkbox_"+t,radioFilter:"ew_tb_radio_"+t,chooseAllFilter:"ew_tb_choose_all_"+t,colsToggleFilter:"ew_tb_toggle_cols"+t}};p.prototype.eachCols=function(w,v){if(!v){v=this.options.colArrays}for(var t=0;t<v.length;t++){var u=v[t];w&&w(t,u);if(u.CHILD_COLS){this.eachCols(w,u.CHILD_COLS)}}};p.prototype.eachData=function(w,v){if(!v){v=this.options.data}for(var t=0;t<v.length;t++){var u=v[t];w&&w(t,u);if(u[this.options.tree.childName]){this.eachData(w,u[this.options.tree.childName])}}};p.prototype.renderBodyAsync=function(x,w){var v=this;var t=this.options;var u=this.getComponents();if(w){w.addClass("ew-tree-table-loading");w.find(".ew-tree-pack").children(".ew-tree-table-arrow").addClass("layui-anim layui-anim-rotate layui-anim-loop")}else{u.$empty.hide();if(t.data&&t.data.length>0){u.$loading.addClass("ew-loading-float")}u.$loading.show()}t.reqData(x,function(y){if(typeof y!=="string"&&y&&y.length>0&&t.tree.isPidData){y=a.pidToChildren(y,t.tree.idName,t.tree.pidName,t.tree.childName)}v.renderBodyData(y,x,w)})};p.prototype.renderBodyData=function(w,A,x){var u;if(typeof w==="string"){u=w;w=[]}var z=this;var C=this.options;var y=this.getComponents();if(A===undefined){C.data=w}else{A[C.tree.childName]=w}var v;if(x){v=parseInt(x.data("indent"))+1;A[C.tree.openName]=true}var t=this.renderBody(w,v,A);if(x){x.nextAll("tr").each(function(){if(parseInt(g(this).data("indent"))<=(v-1)){return false}g(this).remove()});x.after(t).addClass("ew-tree-table-open")}else{y.$tBody.children("tbody").html(t)}c.render(null,y.filter);this.renderNumberCol();if(x){this.checkParentCB(x);x.prevAll("tr").each(function(){var D=parseInt(g(this).data("indent"));if(D<(v-1)){z.checkParentCB(g(this));v=D+1}});x.removeClass("ew-tree-table-loading");var B=x.find(".ew-tree-pack").children(".ew-tree-table-arrow");B.removeClass("layui-anim layui-anim-rotate layui-anim-loop");if(u){x.removeClass("ew-tree-table-open")}else{if(w&&w.length===0){A[C.tree.haveChildName]=false;x.data("have-child",false);B.addClass("ew-tree-table-arrow-hide");B.next(".ew-tree-icon").after(C.tree.getIcon(A)).remove()}}}else{y.$loading.hide();y.$loading.removeClass("ew-loading-float");if(w&&w.length>0){y.$empty.hide()}else{y.$empty.show();if(u){y.$empty.text(u)}else{y.$empty.html(C.text.none)}}}this.checkChooseAllCB();f(y.$view);C.done&&C.done(w)};p.prototype.renderBody=function(z,t,y){var u=this.options;if(!t){t=0}var x="";if(!z||z.length===0){return x}var w=y?!y[u.tree.openName]:undefined;for(var v=0;v<z.length;v++){var A=z[v];A.LAY_INDEX=(y?y.LAY_INDEX+"-":"")+v;x+=this.renderBodyTr(A,t,w);x+=this.renderBody(A[u.tree.childName],t+1,A)}return x};p.prototype.renderBodyTr=function(B,u,x,w){var z=this;var C=this.options;if(!u){u=0}var A=B[C.tree.haveChildName];if(A===undefined){A=B[C.tree.childName]&&B[C.tree.childName].length>0}if(w){w.data("have-child",A?"true":"false");w.data("indent",u);w.removeClass("ew-tree-table-loading")}var v="<tr";var t="";if(A&&B[C.tree.openName]){t+="ew-tree-table-open"}if(x){t+="ew-tree-tb-hide"}v+=(' class="'+t+'"');if(A){v+=(' data-have-child="'+A+'"')}v+=(' data-index="'+B.LAY_INDEX+'"');v+=(' data-indent="'+u+'">');var y=0;this.eachCols(function(E,D){if(D.colGroup){return}v+=z.renderBodyTd(B,u,y,w?w.children("td").eq(y):undefined,D);y++});v+="</tr>";return v};p.prototype.renderBodyTd=function(C,v,A,t,u){if(u.colGroup){return""}var F=this.options;var y=this.getComponents();if(!v){v=0}var B="",E="",D="";if(u.type==="numbers"){B='<span class="ew-tree-table-numbers"></span>'}else{if(u.type==="checkbox"){B=['<input type="checkbox"',C.LAY_CHECKED?' checked="checked"':"",' lay-filter="',y.checkboxFilter,'"',' lay-skin="primary" class="ew-tree-table-checkbox',C.LAY_INDETERMINATE?" ew-form-indeterminate":"",'" />'].join("")}else{if(u.type==="radio"){B=['<input type="radio"',C.LAY_CHECKED?' checked="checked"':"",' lay-filter="',y.radioFilter,'"',' name="',y.radioFilter,'"',' class="ew-tree-table-radio" />'].join("")}else{if(u.templet){if(typeof u.templet==="function"){B=u.templet(C)}else{if(typeof u.templet==="string"){d(g(u.templet).html()).render(C,function(G){B=G})}}}else{if(u.toolbar){if(typeof u.toolbar==="function"){B=u.toolbar(C)}else{if(typeof u.toolbar==="string"){d(g(u.toolbar).html()).render(C,function(G){B=G})}}}else{if(u.field&&C[u.field]!==undefined&&C[u.field]!==null){B=b.escape(C[u.field]||"")}}}}}}if(A===F.tree.iconIndex){for(var w=0;w<v;w++){D+='<span class="ew-tree-table-indent"></span>'}D+='<span class="ew-tree-pack">';var z=C[F.tree.haveChildName];if(z===undefined){z=C[F.tree.childName]&&C[F.tree.childName].length>0}D+=('<i class="ew-tree-table-arrow layui-icon'+(z?"":" ew-tree-table-arrow-hide"));D+=(" "+(F.tree.arrowType||"")+'"></i>');D+=F.tree.getIcon(C);B="<span>"+B+"</span>";if(F.tree.onlyIconControl){B=D+"</span>"+B}else{B=D+B+"</span>"}}E=['<div class="ew-tree-table-cell',u.singleLine===undefined||u.singleLine?" single-line":"",'"',u.align?' align="'+u.align+'"':"",">",' <div class="ew-tree-table-cell-content">',B,"</div>",' <i class="layui-icon layui-icon-close ew-tree-tips-c"></i>',' <div class="layui-table-grid-down" style="display: none;"><i class="layui-icon layui-icon-down"></i></div>',"</div>"].join("");if(t){t.html(E)}var x="<td";if(u.field){x+=(' data-field="'+u.field+'"')}if(u.edit){x+=(' data-edit="'+u.edit+'"')}if(u.type){x+=(' data-type="'+u.type+'"')}if(u.key){x+=(' data-key="'+u.key+'"')}if(u.style){x+=(' style="'+u.style+'"')}if(u["class"]){x+=(' class="'+u["class"]+(u.hide?" layui-hide":"")+'"')}else{if(u.hide){x+=(' class="layui-hide"')}}x+=(">"+E+"</td>");return x};p.prototype.renderBodyTh=function(){var t=this.options;var v=this.getComponents();var u=[];g.each(t.cols,function(x,w){u.push("<tr>");g.each(w,function(A,z){u.push("<th");if(z.colspan){u.push(' colspan="'+z.colspan+'"')}if(z.rowspan){u.push(' rowspan="'+z.rowspan+'"')}if(z.type){u.push(' data-type="'+z.type+'"')}if(z.key){u.push(' data-key="'+z.key+'"')}if(z.parentKey){u.push(' data-parent="'+z.parentKey+'"')}if(z.hide){u.push(' class="layui-hide"')}u.push(">");u.push('<div class="ew-tree-table-cell'+(z.singleLine===undefined||z.singleLine?" single-line":"")+'"');if(z.thAlign||z.align){u.push(' align="'+(z.thAlign||z.align)+'"')}u.push(">");u.push('<div class="ew-tree-table-cell-content">');var y='<input type="checkbox" lay-filter="'+v.chooseAllFilter+'" lay-skin="primary" class="ew-tree-table-checkbox"/>';if(z.type==="checkbox"){u.push(y)}else{u.push(z.title||"")}u.push('</div><i class="layui-icon layui-icon-close ew-tree-tips-c"></i>');u.push('<div class="layui-table-grid-down" style="display: none;"><i class="layui-icon layui-icon-down"></i></div></div>');if(!z.colGroup&&!z.unresize){u.push('<span class="ew-tb-resize"></span>')}u.push("</th>")});u.push("</tr>")});return u.join("")};p.prototype.resize=function(z){var t=this.options;var x=this.getComponents();var v=1,u=1,A=true,w=0;this.eachCols(function(B,C){if(C.colGroup||C.hide){return}if(C.width){u+=(C.width+1);if(C.minWidth){if(C.width<C.minWidth){C.width=C.minWidth}}else{if(C.width<t.cellMinWidth){C.width=t.cellMinWidth}}}else{A=false}if(C.width){v+=(C.width+1)}else{if(C.minWidth){v+=(C.minWidth+1);w+=C.minWidth}else{v+=(t.cellMinWidth+1);w+=t.cellMinWidth}}});if(v){x.$tHead.css("min-width",v);x.$tBody.css("min-width",v)}else{x.$tHead.css("min-width","auto");x.$tBody.css("min-width","auto")}if(A){x.$tHead.css("width",u);x.$tBody.css("width",u)}else{x.$tHead.css("width","100%");x.$tBody.css("width","100%")}var y=[];this.eachCols(function(B,C){if(C.colGroup||C.hide){return}y.push("<col");if(C.width){y.push(' width="'+C.width+'"')}else{if(C.minWidth){y.push(' width="'+(C.minWidth/w*100).toFixed(2)+'%"')}else{y.push(' width="'+(t.cellMinWidth/w*100).toFixed(2)+'%"')}}if(C.type){y.push(' data-type="'+C.type+'"')}if(C.key){y.push(' data-key="'+C.key+'"')}y.push("/>")});y=y.join("");if(z){return"<colgroup>"+y+"</colgroup>"}x.$table.children("colgroup").html(y)};p.prototype.getDataByTr=function(v){var w,t;if(typeof v!=="string"&&typeof v!=="number"){if(v){t=v.data("index")}}else{t=v}if(t===undefined){return}if(typeof t==="number"){t=[t]}else{t=t.split("-")}for(var u=0;u<t.length;u++){if(w){w=w[this.options.tree.childName][t[u]]}else{w=this.options.data[t[u]]}}return w};p.prototype.checkSubCB=function(y,x){var w=this;var v=this.getComponents();var t=-1,u;if(y.is("tbody")){u=y.children("tr")}else{t=parseInt(y.data("indent"));u=y.nextAll("tr")}u.each(function(){if(parseInt(g(this).data("indent"))<=t){return false}var A=g(this).children("td").find('input[lay-filter="'+v.checkboxFilter+'"]');A.prop("checked",x);A.removeClass("ew-form-indeterminate");if(x){A.next(".layui-form-checkbox").addClass("layui-form-checked")}else{A.next(".layui-form-checkbox").removeClass("layui-form-checked")}var z=w.getDataByTr(g(this));z.LAY_CHECKED=x;z.LAY_INDETERMINATE=false})};p.prototype.checkParentCB=function(x){var u=this.options;var w=this.getComponents();var z=this.getDataByTr(x);var y=0,v=0;if(z[u.tree.childName]){function t(C){for(var B=0;B<C.length;B++){if(C[B].LAY_CHECKED){y++}else{v++}if(C[B][u.tree.childName]){t(C[B][u.tree.childName])}}}t(z[u.tree.childName])}var A=x.children("td").find('input[lay-filter="'+w.checkboxFilter+'"]');if(y>0&&v===0){A.prop("checked",true);A.removeClass("ew-form-indeterminate");A.next(".layui-form-checkbox").addClass("layui-form-checked");z.LAY_CHECKED=true;z.LAY_INDETERMINATE=false}else{if(y===0&&v>0){A.prop("checked",false);A.removeClass("ew-form-indeterminate");A.next(".layui-form-checkbox").removeClass("layui-form-checked");z.LAY_CHECKED=false;z.LAY_INDETERMINATE=false}else{if(y>0&&v>0){A.prop("checked",true);A.data("indeterminate","true");A.addClass("ew-form-indeterminate");A.next(".layui-form-checkbox").addClass("layui-form-checked");z.LAY_CHECKED=true;z.LAY_INDETERMINATE=true}}}};p.prototype.checkChooseAllCB=function(){var u=this.options;var w=this.getComponents();var x=0,v=0;function t(A){for(var z=0;z<A.length;z++){if(A[z].LAY_CHECKED){x++}else{v++}if(A[z][u.tree.childName]){t(A[z][u.tree.childName])}}}t(u.data);var y=w.$view.find('input[lay-filter="'+w.chooseAllFilter+'"]');if(x>0&&v===0){y.prop("checked",true);y.removeClass("ew-form-indeterminate");y.next(".layui-form-checkbox").addClass("layui-form-checked")}else{if((x===0&&v>0)||(x===0&&v===0)){y.prop("checked",false);y.removeClass("ew-form-indeterminate");y.next(".layui-form-checkbox").removeClass("layui-form-checked")}else{if(x>0&&v>0){y.prop("checked",true);y.addClass("ew-form-indeterminate");y.next(".layui-form-checkbox").addClass("layui-form-checked")}}}};p.prototype.renderNumberCol=function(){this.getComponents().$tBody.children("tbody").children("tr").each(function(t){g(this).children("td").find(".ew-tree-table-numbers").text(t+1)})};p.prototype.getIndexById=function(v){var t=this.options;function u(x,y){for(var w=0;w<x.length;w++){if(x[w][t.tree.idName]==v){return y!==undefined?y+"-"+w:w}if(x[w][t.tree.childName]){return u(x[w][t.tree.childName],y!==undefined?y+"-"+w:w)}}}return u(t.data)};p.prototype.expand=function(x,u){var w=this.getComponents();var v=w.$table.children("tbody").children('tr[data-index="'+this.getIndexById(x)+'"]');if(!v.hasClass("ew-tree-table-open")){v.children("td").find(".ew-tree-pack").trigger("click")}if(u===false){return}var t=parseInt(v.data("indent"));v.prevAll("tr").each(function(){var y=parseInt(g(this).data("indent"));if(y<t){if(!g(this).hasClass("ew-tree-table-open")){g(this).children("td").find(".ew-tree-pack").trigger("click")}t=y}})};p.prototype.fold=function(v){var u=this.getComponents();var t=u.$table.children("tbody").children('tr[data-index="'+this.getIndexById(v)+'"]');if(t.hasClass("ew-tree-table-open")){t.children("td").find(".ew-tree-pack").trigger("click")}};p.prototype.expandAll=function(){this.getComponents().$table.children("tbody").children("tr").each(function(){if(!g(this).hasClass("ew-tree-table-open")){g(this).children("td").find(".ew-tree-pack").trigger("click")}})};p.prototype.foldAll=function(){this.getComponents().$table.children("tbody").children("tr").each(function(){if(g(this).hasClass("ew-tree-table-open")){g(this).children("td").find(".ew-tree-pack").trigger("click")}})};p.prototype.getData=function(){return this.options.data};p.prototype.reload=function(t){this.initOptions(this.options?g.extend(true,this.options,t):t);this.init();this.bindEvents()};p.prototype.checkStatus=function(t){if(t===undefined){t=true}var u=[];this.eachData(function(v,w){if((t||!w.LAY_INDETERMINATE)&&w.LAY_CHECKED){u.push(g.extend({isIndeterminate:w.LAY_INDETERMINATE},w))}});return u};p.prototype.setChecked=function(u){var w=this;var v=this.getComponents();var t=v.$table.find('input[lay-filter="'+v.radioFilter+'"]');if(t.length>0){t.each(function(){var x=w.getDataByTr(g(this).parentsUntil("tr").parent());if(x&&u[u.length-1]==x[w.options.tree.idName]){g(this).next(".layui-form-radio").trigger("click");return false}})}else{v.$table.find('input[lay-filter="'+v.checkboxFilter+'"]').each(function(){var C=g(this);var y=C.next(".layui-form-checkbox");var z=C.prop("checked");var B=C.hasClass("ew-form-indeterminate");var A=w.getDataByTr(C.parentsUntil("tr").parent());for(var x=0;x<u.length;x++){if(A&&u[x]==A[w.options.tree.idName]){if(A[w.options.tree.childName]&&A[w.options.tree.childName].length>0){continue}if(!z||B){y.trigger("click")}}}})}};p.prototype.removeAllChecked=function(){this.checkSubCB(this.getComponents().$table.children("tbody"),false)};p.prototype.exportData=function(w){var y=this.getComponents();if("show"===w){y.$toolbar.find(".layui-table-tool-panel").remove();y.$toolbar.find('[lay-event="LAYTABLE_EXPORT"]').append(['<ul class="layui-table-tool-panel">',' <li data-type="csv">导出到 Csv 文件</li>',' <li data-type="xls">导出到 Excel 文件</li>',"</ul>"].join(""))}else{if(o.ie){return layer.msg("不支持ie导出")}if(!w){w="xls"}var u=[],t=[];this.eachCols(function(A,B){if(B.type!=="normal"||B.hide){return}u.push(B.title||"")});y.$tBody.children("tbody").children("tr").each(function(){var A=[];g(this).children("td").each(function(){var B=g(this);if(B.data("type")!=="normal"||B.hasClass("layui-hide")){return true}A.push(B.text().trim().replace(/,/g,","))});t.push(A.join(","))});var v=document.createElement("a");var x=encodeURIComponent(u.join(",")+"\r\n"+t.join("\r\n"));var z=({csv:"text/csv",xls:"application/vnd.ms-excel"})[w];v.href="data:"+z+";charset=utf-8,\ufeff"+x;v.download=(this.options.title||"table")+"."+w;document.body.appendChild(v);v.click();document.body.removeChild(v)}};p.prototype.printTable=function(){var w=this.getComponents();var z=w.$tHead.children("thead").html();if(!z){z=w.$tBody.children("thead").html()}var x=w.$tBody.children("tbody").html();var v=w.$tBody.children("colgroup").html();var u=g(['<table class="ew-tree-table-print">'," <colgroup>",v,"</colgroup>"," <thead>",z,"</thead>"," <tbody>",x,"</tbody>","</table>"].join(""));u.find('col[data-type="checkbox"],col[data-type="radio"],col[data-type="tool"]').remove();u.find('td[data-type="checkbox"],td[data-type="radio"],td[data-type="tool"],.layui-hide').remove();function A(F){var C=F.data("parent"),D;if(!C){return}var E=u.children("thead").children("tr").children('[data-key="'+C+'"]');var G=parseInt(E.attr("colspan"))-1;E.attr("colspan",G);if(G===0){E.remove()}A(E)}u.find('th[data-type="checkbox"],th[data-type="radio"],th[data-type="tool"]').each(function(){A(g(this))}).remove();var t=["<style>"," /* 打印表格样式 */"," .ew-tree-table-print {"," border: none;"," border-collapse: collapse;"," width: 100%;"," table-layout: fixed;"," }"," .ew-tree-table-print td, .ew-tree-table-print th {"," color: #555;"," font-size: 14px;"," padding: 9px 15px;"," word-break: break-all;"," border: 1px solid #888;"," text-align: left;"," }"," .ew-tree-table-print .ew-tree-table-cell {"," min-height: 20px;"," }"," /* 序号列样式 */",' .ew-tree-table-print td[data-type="numbers"], .ew-tree-table-print th[data-type="numbers"] {'," padding-left: 0;"," padding-right: 0;"," }"," /* 单/复选框列样式 */",' .ew-tree-table-print td[data-type="tool"], .ew-tree-table-print th[data-type="tool"], ',' .ew-tree-table-print td[data-type="checkbox"], .ew-tree-table-print th[data-type="checkbox"], ',' .ew-tree-table-print td[data-type="radio"], .ew-tree-table-print th[data-type="radio"] {'," border: none;"," }"," .ew-tree-table-print td.layui-hide + td, .ew-tree-table-print th.layui-hide + th, ",' .ew-tree-table-print td[data-type="tool"] + td, .ew-tree-table-print th[data-type="tool"] + th, ',' .ew-tree-table-print td[data-type="checkbox"] + td, .ew-tree-table-print th[data-type="checkbox"] + th, ',' .ew-tree-table-print td[data-type="radio"] + td, .ew-tree-table-print th[data-type="radio"] + th {'," border-left: none;"," }"," /* 不显示的元素 */"," .layui-hide, ",' .ew-tree-table-print td[data-type="tool"] *, .ew-tree-table-print th[data-type="tool"] *, ',' .ew-tree-table-print td[data-type="checkbox"] *, .ew-tree-table-print th[data-type="checkbox"] *, ',' .ew-tree-table-print td[data-type="radio"] *, .ew-tree-table-print th[data-type="radio"] *, '," .layui-table-grid-down, .ew-tree-tips-c, .ew-tree-icon, .ew-tree-table-arrow.ew-tree-table-arrow-hide {"," display: none;"," }"," /* tree缩进 */"," .ew-tree-table-indent {"," padding-left: 13px;"," }"," /* 箭头 */"," .ew-tree-table-arrow {"," position: relative;"," padding-left: 13px;"," }"," .ew-tree-table-arrow:before {",' content: "";'," border: 5px solid transparent;"," border-top-color: #666;"," position: absolute;"," left: 0;"," top: 6px;"," }","</style>"].join("");var y=window.open("","_blank");y.focus();var B=y.document;B.open();B.write(u[0].outerHTML+t);B.close();y.print();y.close()};p.prototype.toggleCol=function(A,z,B){var w=this.getComponents();if(A===undefined){w.$toolbar.find(".layui-table-tool-panel").remove();var x=['<ul class="layui-table-tool-panel">'];this.eachCols(function(D,E){if(E.type!=="normal"){return}x.push('<li><input type="checkbox" lay-skin="primary"');x.push(' lay-filter="'+w.colsToggleFilter+'"');x.push(' value="'+E.key+'" title="'+b.escape(E.title||"")+'"');x.push((E.hide?"":" checked")+"></li>")});w.$toolbar.find('[lay-event="LAYTABLE_COLS"]').append(x.join("")+"</ul>");c.render("checkbox",w.filter)}else{if(B){var u=w.$table.children("tbody").children("tr").children('[data-key="'+B+'"]');var C=w.$table.children("thead").children("tr").children('[data-key="'+B+'"]');if(A){u.removeClass("layui-hide");C.removeClass("layui-hide")}else{u.addClass("layui-hide");C.addClass("layui-hide")}var y=B.split("-");var v=this.options.cols[y[0]][y[1]];v.hide=!A;function t(G){var D=G.data("parent"),E;if(!D){return}var F=w.$table.children("thead").children("tr").children('[data-key="'+D+'"]');var H=F.attr("colspan");A?H++:H--;F.attr("colspan",H);if(H===0){F.addClass("layui-hide")}else{F.removeClass("layui-hide")}t(F)}t(C);this.eachCols(function(D,E){if(E.key===B){E.hide=v.hide}});this.resize()}}};p.prototype.filterData=function(y){var A=this.getComponents();A.$loading.show();if(this.options.data.length>0){A.$loading.addClass("ew-loading-float")}var x=A.$table.children("tbody").children("tr");var u=[];if(typeof y==="string"){x.each(function(){var B=g(this).data("index");g(this).children("td").each(function(){if(g(this).text().indexOf(y)!==-1){u.push(B);return false}})})}else{for(var w=0;w<y.length;w++){u.push(this.getIndexById(y[w]))}}x.addClass("ew-tree-table-filter-hide");for(var v=0;v<u.length;v++){var z=x.filter('[data-index="'+u[v]+'"]');z.removeClass("ew-tree-table-filter-hide");var t=parseInt(z.data("indent"));z.nextAll("tr").each(function(){if(parseInt(g(this).data("indent"))<=t){return false}g(this).removeClass("ew-tree-table-filter-hide")});if(z.hasClass("ew-tree-table-open")){i(z)}z.prevAll("tr").each(function(){var B=parseInt(g(this).data("indent"));if(B<t){g(this).removeClass("ew-tree-table-filter-hide");if(!g(this).hasClass("ew-tree-table-open")){i(g(this))}t=B}})}A.$loading.hide();A.$loading.removeClass("ew-loading-float");if(u.length===0){A.$empty.show()}f(A.$view)};p.prototype.clearFilter=function(){var t=this.getComponents();t.$table.children("tbody").children("tr").removeClass("ew-tree-table-filter-hide");if(this.options.data.length>0){t.$empty.hide()}f(t.$view)};p.prototype.refresh=function(x,v){if(l(x)==="Array"){v=x;x=undefined}var u=this.getComponents();var w,t;if(x!==undefined){t=u.$table.children("tbody").children('tr[data-index="'+this.getIndexById(x)+'"]');w=this.getDataByTr(t)}if(v){if(this.data.length>0){u.$loading.addClass("ew-loading-float")}u.$loading.show();if(v.length>0&&this.options.tree.isPidData){this.renderBodyData(a.pidToChildren(v,this.options.tree.idName,this.options.tree.pidName,this.options.tree.childName),w,t)}else{this.renderBodyData(v,w,t)}}else{this.renderBodyAsync(w,t)}};p.prototype.del=function(x,u){if(u===undefined){u=this.getIndexById(x)}var t=(typeof u==="number"?[u]:u.split("-"));var w=this.options.data;if(t.length>1){for(var v=0;v<t.length-1;v++){w=w[parseInt(t[v])][this.options.tree.childName]}}w.splice(t[t.length-1],1)};p.prototype.update=function(u,t){g.extend(true,this.getDataByTr(this.getIndexById(u)),t)};function i(v){var t=parseInt(v.data("indent"));var u=v.hasClass("ew-tree-table-open");if(u){v.removeClass("ew-tree-table-open");v.nextAll("tr").each(function(){if(parseInt(g(this).data("indent"))<=t){return false}g(this).addClass("ew-tree-tb-hide")})}else{v.addClass("ew-tree-table-open");var w;v.nextAll("tr").each(function(){var x=parseInt(g(this).data("indent"));if(x<=t){return false}if(w!==undefined&&x>w){return true}g(this).removeClass("ew-tree-tb-hide");if(!g(this).hasClass("ew-tree-table-open")){w=parseInt(g(this).data("indent"))}else{w=undefined}})}f(v.parentsUntil(".ew-tree-table").last().parent());return u}function f(w){var t=w.children(".ew-tree-table-head");var u=w.children(".ew-tree-table-box");var v=u.width()-u.prop("clientWidth");t.css("border-right",(v>0?v:0)+"px solid #f2f2f2")}g(window).resize(function(){g(".ew-tree-table").each(function(){f(g(this));var u=g(this).children(".ew-tree-table-box");var t=u.data("full");if(t&&o.ie&&o.ie<10){u.css("height",m()-t)}})});g(document).on("mouseenter",".ew-tree-table-cell.single-line",function(){var t=g(this).children(".ew-tree-table-cell-content");if(t.prop("scrollWidth")>t.outerWidth()){g(this).children(".layui-table-grid-down").show()}}).on("mouseleave",".ew-tree-table-cell.single-line",function(){g(this).children(".layui-table-grid-down").hide()});g(document).on("click",".ew-tree-table-cell>.layui-table-grid-down",function(w){w.stopPropagation();j();var u=g(this).parent();u.addClass("ew-tree-tips-open");u.children(".layui-table-grid-down").hide();var t=u.parent().outerWidth()+4;if(u.outerWidth()<t){u.children(".ew-tree-table-cell-content").css({"width":t,"max-width":t})}var v=u.parents().filter(".ew-tree-table-box");if(v.length===0){v=u.parents().filter(".ew-tree-table-head")}if(v.length===0){return}if((u.outerWidth()+u.offset().left)+20>v.offset().left+v.outerWidth()){u.addClass("ew-show-left")}if((u.outerHeight()+u.offset().top+10)>v.offset().top+v.outerHeight()){u.addClass("ew-show-bottom")}});g(document).on("click",".ew-tree-table-cell>.ew-tree-tips-c",function(){j()});g(document).on("click",function(){j();g(".ew-tree-table .layui-table-tool-panel").remove()});g(document).on("click",".ew-tree-table-cell.ew-tree-tips-open",function(t){t.stopPropagation()});function j(){g(".ew-tree-table-cell").removeClass("ew-tree-tips-open ew-show-left ew-show-bottom");g(".ew-tree-table-cell>.ew-tree-table-cell-content").css({"width":"","max-width":""})}g(document).on("mousedown",".ew-tb-resize",function(x){layui.stope(x);var v=g(this);v.attr("move","true");var u=v.parent().data("key");v.data("x",x.clientX);var t=v.parent().parent().parent().parent().children("colgroup").children('col[data-key="'+u+'"]').attr("width");if(!t||t.toString().indexOf("%")!==-1){t=v.parent().outerWidth()}v.data("width",t);g("body").addClass("ew-tree-table-resizing")}).on("mousemove",function(B){var y=g('.ew-tree-table .ew-tb-resize[move="true"]');if(y.length===0){return}layui.stope(B);var t=y.data("x");var v=y.data("width");var u=parseFloat(v)+B.clientX-parseFloat(t);if(u<=0){u=1}var z=k[y.parentsUntil(".ew-tree-table").last().parent().attr("lay-filter")];var A=y.parent().data("key");var C=A.split("-");z.options.cols[C[0]][C[1]].width=u;z.eachCols(function(w,x){if(x.key===A){x.width=u}});z.resize()}).on("mouseup",function(t){g('.ew-tree-table .ew-tb-resize[move="true"]').attr("move","false");g("body").removeClass("ew-tree-table-resizing")}).on("mouseleave",function(t){g('.ew-tree-table .ew-tb-resize[move="true"]').attr("move","false");g("body").removeClass("ew-tree-table-resizing")});function q(x,u,z){var y=[];for(var w=0;w<x.length;w++){var t=false;for(var v=0;v<x.length;v++){if(x[w][z]==x[v][u]){t=true;break}}if(!t){y.push(x[w][z])}}return y}function n(u,v){if(l(v)==="Array"){for(var t=0;t<v.length;t++){if(u==v[t]){return true}}}return u==v}function l(t){if(t===null){return"Null"}if(t===undefined){return"Undefined"}return Object.prototype.toString.call(t).slice(8,-1)}function m(){return document.documentElement.clientHeight||document.body.clientHeight}var a={render:function(t){return new p(t)},reload:function(u,t){k[u].reload(t)},on:function(t,u){return layui.onevent.call(this,h,t,u)},pidToChildren:function(z,u,A,t,x){if(!t){t="children"}var y=[];for(var w=0;w<z.length;w++){if(z[w][u]==z[w][A]){return console.error("第"+w+"条数据的"+u+"与"+A+"相同",z[w])}if(x===undefined){x=q(z,u,A)}if(n(z[w][A],x)){var v=this.pidToChildren(z,u,A,t,z[w][u]);if(v.length>0){z[w][t]=v}y.push(z[w])}}return y}};g("head").append(['<style id="ew-tree-table-css">',"/** 最外层容器 */",".ew-tree-table {"," margin: 10px 0;"," position: relative;"," border: 1px solid #e6e6e6;"," border-bottom: none;"," border-right: none;","}",".ew-tree-table:before, .ew-tree-table:after, .ew-tree-table .ew-tree-table-head:after {",' content: "";'," background-color: #e6e6e6;"," position: absolute;"," right: 0;"," bottom: 0;","}",".ew-tree-table:before {"," width: 1px;"," top: 0;"," z-index: 1;","}",".ew-tree-table:after, .ew-tree-table .ew-tree-table-head:after {"," height: 1px;"," left: 0;","}",".ew-tree-table .layui-table {"," margin: 0;"," position: relative;"," table-layout: fixed;","}","/** 表格 */",".ew-tree-table .layui-table td, .ew-tree-table .layui-table th {"," border-top: none;"," border-left: none;"," padding: 0 !important;","}",".ew-tree-table .ew-tree-table-box {"," overflow: auto;"," position: relative;","}",".ew-tree-table .ew-tree-table-head {"," overflow: hidden;"," box-sizing: border-box;"," background-color: #f2f2f2;"," position: relative;","}","/** loading */",".ew-tree-table div.ew-tree-table-loading {"," padding: 10px 0;"," text-align: center;","}",".ew-tree-table div.ew-tree-table-loading > i {"," color: #999;"," font-size: 30px;","}",".ew-tree-table div.ew-tree-table-loading.ew-loading-float {"," position: absolute;"," top: 0;"," left: 0;"," right: 0;","}","/** 空数据 */",".ew-tree-table .ew-tree-table-empty {"," color: #666;"," font-size: 14px;"," padding: 18px 0;"," text-align: center;"," display: none;","}","/** 单元格 */",".ew-tree-table-cell.ew-tree-tips-open {"," position: absolute;"," top: 0;"," left: 0;"," padding: 0;"," z-index: 9999;"," background-color: #fff;"," box-shadow: 3px 3px 8px rgba(0, 0, 0, .15);","}","thead .ew-tree-table-cell.ew-tree-tips-open {"," background-color: #f2f2f2;","}",".ew-tree-table-cell.ew-tree-tips-open.ew-show-left {"," right: 0;"," left: auto;"," box-shadow: -3px 3px 8px rgba(0, 0, 0, .15);","}",".ew-tree-table-cell.ew-tree-tips-open.ew-show-bottom {"," bottom: 0;"," top: auto;"," box-shadow: 3px -3px 8px rgba(0, 0, 0, .15);","}",".ew-tree-table-cell.ew-tree-tips-open.ew-show-left.ew-show-bottom {"," box-shadow: -3px -3px 8px rgba(0, 0, 0, .15);","}",".ew-tree-table-cell > .ew-tree-tips-c {"," position: absolute;"," right: -6px;"," top: -3px;"," width: 22px;"," height: 22px;"," line-height: 22px;"," font-size: 16px;"," color: #fff;"," background-color: #666;"," border-radius: 50%;"," text-align: center;"," cursor: pointer;"," display: none;","}","table tr:first-child .ew-tree-table-cell > .ew-tree-tips-c {"," top: 0;","}",".ew-tree-table-cell.ew-tree-tips-open > .ew-tree-tips-c {"," display: block;","}",".ew-tree-table-cell.ew-tree-tips-open.ew-show-left > .ew-tree-tips-c {"," left: -6px;"," right: auto;","}",".ew-tree-table-cell > .ew-tree-table-cell-content {"," padding: 5px 15px;"," line-height: 28px;","}",'[lay-size="lg"] .ew-tree-table-cell > .ew-tree-table-cell-content {'," line-height: 40px;","}",'[lay-size="sm"] .ew-tree-table-cell > .ew-tree-table-cell-content {'," padding: 1px 15px;","}",".ew-tree-table-cell.single-line > .ew-tree-table-cell-content {"," overflow: hidden;"," white-space: nowrap;"," text-overflow: ellipsis;","}",".ew-tree-table-cell.ew-tree-tips-open > .ew-tree-table-cell-content {"," overflow: auto;"," padding: 9px 15px;"," height: auto;"," min-height: 100%;"," max-height: 110px;"," line-height: inherit;"," max-width: 260px;"," width: 200px;"," width: max-content;"," width: -moz-max-content;"," box-sizing: border-box;"," white-space: normal;","}",".ew-tree-table-cell > .layui-table-grid-down {"," box-sizing: border-box;","}","/** 图标列 */",".ew-tree-table .ew-tree-pack {"," cursor: pointer;"," line-height: 16px;","}",".ew-tree-table .ew-tree-pack > .layui-icon, .ew-tree-table .ew-tree-pack > .ew-tree-icon {"," margin-right: 5px;","}",".ew-tree-table .ew-tree-pack > * {"," vertical-align: middle;","}","/* 缩进 */",".ew-tree-table .ew-tree-table-indent {"," margin-right: 5px;"," padding-left: 16px;","}","/* 箭头 */",".ew-tree-table .ew-tree-table-arrow:before {",' content: "\\e623";',"}",".ew-tree-table .ew-tree-table-open .ew-tree-table-arrow:before {",' content: "\\e625";',"}",".ew-tree-table .ew-tree-table-arrow.arrow2 {"," font-size: 12px;"," font-weight: 600;"," line-height: 16px;"," height: 16px;"," width: 16px;"," display: inline-block;"," text-align: center;"," color: #888;","}",".ew-tree-table .ew-tree-table-arrow.arrow2:before {",' content: "\\e602";',"}",".ew-tree-table .ew-tree-table-open .ew-tree-table-arrow.arrow2:before {",' content: "\\e61a";',"}",".ew-tree-table-arrow.ew-tree-table-arrow-hide {"," visibility: hidden;","}","/* 箭头变加载中状态 */",".ew-tree-table tr.ew-tree-table-loading > td .ew-tree-table-arrow:before {",' content: "\\e63d" !important;',"}",".ew-tree-table tr.ew-tree-table-loading > td .ew-tree-table-arrow {"," margin-right: 0;","}",".ew-tree-table tr.ew-tree-table-loading > td .ew-tree-table-arrow + * {"," margin-left: 5px;","}",".ew-tree-table tr.ew-tree-table-loading * {"," pointer-events: none !important;","}","/** 折叠行 */",".ew-tree-table .ew-tree-tb-hide {"," display: none;","}","/** 特殊列调整 */",'.ew-tree-table td[data-type="numbers"] > .ew-tree-table-cell,','.ew-tree-table th[data-type="numbers"] > .ew-tree-table-cell,','.ew-tree-table td[data-type="checkbox"] > .ew-tree-table-cell,','.ew-tree-table th[data-type="checkbox"] > .ew-tree-table-cell,','.ew-tree-table td[data-type="radio"] > .ew-tree-table-cell,','.ew-tree-table th[data-type="radio"] > .ew-tree-table-cell,','.ew-tree-table td[data-type="space"] > .ew-tree-table-cell,','.ew-tree-table th[data-type="space"] > .ew-tree-table-cell {'," padding-left: 0;"," padding-right: 0;","}","/* 单元格内表单元素样式调整 */",".ew-tree-table .layui-form-switch",".ew-tree-table .layui-form-radio {"," margin: 0;","}","/* checkbox列调整 */",".ew-tree-table-checkbox + .layui-form-checkbox {"," padding: 0;","}",".ew-tree-table-checkbox + .layui-form-checkbox > .layui-icon {"," font-weight: 600;"," color: transparent;"," transition: background-color .1s linear;"," -webkit-transition: background-color .1s linear;","}",".ew-tree-table-checkbox + .layui-form-checkbox.layui-form-checked > .layui-icon {"," color: #fff;","}","/* checkbox半选状态 */",".ew-form-indeterminate + .layui-form-checkbox .layui-icon:before {",' content: "";'," width: 10px;"," height: 2px;"," background-color: #f1f1f1;"," position: absolute;"," top: 50%;"," left: 50%;"," margin: -1px 0 0 -5px;","}","/* radio列调整 */",".ew-tree-table-radio + .layui-form-radio {"," margin: 0;"," padding: 0;"," height: 20px;"," line-height: 20px;","}",".ew-tree-table-radio + .layui-form-radio > i {"," margin: 0;"," height: 20px;"," font-size: 20px;"," line-height: 20px;","}","/** 单元格编辑 */",".ew-tree-table .layui-table td[data-edit] {"," cursor: text;","}",".ew-tree-table .ew-tree-table-edit {"," position: absolute;"," left: 0;"," top: 0;"," width: 100%;"," height: 100%;"," border-radius: 0;"," box-shadow: 1px 1px 20px rgba(0, 0, 0, .15);","}",".ew-tree-table .ew-tree-table-edit:focus {"," border-color: #5FB878 !important;","}",".ew-tree-table .ew-tree-table-edit.layui-form-danger {"," border-color: #FF5722 !important;","}","/** 搜索数据隐藏行 */",".ew-tree-table tr.ew-tree-table-filter-hide {"," display: none !important;","}","/** 头部工具栏 */",".ew-tree-table .ew-tree-table-tool {"," min-height: 50px;"," line-height: 30px;"," padding: 10px 15px;"," box-sizing: border-box;"," background-color: #f2f2f2;"," border-bottom: 1px solid #e6e6e6;","}",".ew-tree-table .ew-tree-table-tool .ew-tree-table-tool-right {"," float: right;","}",".ew-tree-table .ew-tree-table-tool .ew-tree-table-tool-item {"," position: relative;"," color: #333;"," width: 26px;"," height: 26px;"," line-height: 26px;"," text-align: center;"," margin-left: 10px;"," display: inline-block;"," border: 1px solid #ccc;"," box-sizing: border-box;"," vertical-align: middle;"," -webkit-transition: .3s all;"," transition: .3s all;"," cursor: pointer;","}",".ew-tree-table .ew-tree-table-tool .ew-tree-table-tool-item:first-child {"," margin-left: 0;","}",".ew-tree-table .ew-tree-table-tool .ew-tree-table-tool-item:hover {"," border-color: #999;","}",".ew-tree-table .ew-tree-table-tool-right .layui-table-tool-panel {"," left: auto;"," right: -1px;"," z-index: 9999;","}","/* 列宽拖拽调整 */",".ew-tree-table .ew-tb-resize {"," position: absolute;"," right: 0;"," top: 0;"," bottom: 0;"," width: 10px;"," cursor: col-resize;","}",".ew-tree-table-resizing {"," cursor: col-resize;"," -ms-user-select: none;"," -moz-user-select: none;"," -webkit-user-select: none;"," user-select: none;","}","/* 辅助样式 */",".ew-tree-table .layui-form-switch {"," margin: 0;","}",".ew-tree-table .pd-tb-0 {"," padding-top: 0 !important;"," padding-bottom: 0 !important;","}",".ew-tree-table .break-all {"," word-break: break-all !important;","}","/** 扩展图标 */",".ew-tree-table .ew-tree-icon-folder:after, .ew-tree-table .ew-tree-icon-file:after {",' content: "";'," padding: 2px 10px;"," -webkit-background-size: cover;"," -moz-background-size: cover;"," -o-background-size: cover;"," background-size: cover;"," background-repeat: no-repeat;",' background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAE6UlEQVR4Xu2ZPYhcVRiGny9hC0FsTEBCGkFTWIQE/IlpgmKpWAiLyR0XLbYTxEKxkCAEhRCxEOwsjJnJioKIYClWKgqiskIIaCoLYyASVJT87JGspN37LrOXvec777Tzzrnvz7Nn2dnAr6YbiKbTOzwGoHEIDIABaLyBxuP7BjAAjTfQeHzfAAag8QYaj+8bwAA03kDj8X0DGIDGG2g8/lw3QFlhD9fZN7oOF7gYT3NudL5GaGjTAJQP2c1VXgIOExyGkf4/oXCe4I3oeH+EvY/G0qYAKFOWCV4Hdo8mQb+RL7jBE7HE3/3S9hQyAGXGCeDVSiv6lqscief4t1L/g9mWAChTHiD4ZrTXvVbPu9GxrEnbUWkAzPgeOJCglsXo+ChBji2L0AtAmfEgrP/0Z3hdZoF7Y5HLGcJsRQYFgLeAF7fiYSM540x0LI3Ey7bb6AdgytcEh7bd6VYa2MGhOJrmVpurmX4AZlwCds31lPF9+AI32O8/DYUvccqUKwR3jG/DuR29Gd36F1pNv/pvgKwAFK5RuC+e4eeWCWgXgJurFz6LCY8bgA0aSPwr4P/UhVNc43ir3xK2fQPcAr/wO/AewU/Ar6xRqroVdvAnC6zGIlc369sAbLax8er/ofAJOzkVR9e/uZVeBkCqqTrRyeh4RXFtAJSWatQUno0Jp/usG4C+hup9/yJ72BuPcH2jCAag3oEV50vRccYAKFXl1LwdHS8YgJzj9qcqfBoTnjQA/VVlVXwXHfcbgKzz9uf6IToOGoD+orIqDEDWZcVcBkAsKqvMAGRdVsxlAMSissoMQNZlxVwGQCwqq8wAZF1WzGUAxKKyygxA1mXFXAZALCqrzABkXVbMZQDEorLKDEDWZcVcBkAsKqvMAGRdVsxlAMSissoMQNZlxVwGQCwqq8wAZF1WzGUAxKKyygxA1mXFXAZALCqrzABkXVbMZQDEorLKDEDWZcVcBkAsKqvMAGRdVsxlAMSissoMQNZlxVwGQCwqq8wAZF1WzGUAxKKyygxA1mXFXAZALCqrzABkXVbMZQDEorLKDEDWZcVcBkAsKqvMAGRdVsxlAMSissoMQNZlxVwGQCwqq8wAZF1WzGUAxKKyygxA1mXFXAZALCqrzABkXVbMZQDEorLKDEDWZcVcBkAsKqvMAGRdVsxlAMSissoMQNZlxVwGQCwqq8wAZF1WzGUAxKKyygxA1mXFXAZALCqrzABkXVbMZQDEorLKDEDWZcVcBkAsKqvMAGRdVsxlAMSissoMQNZlxVwGQCwqq8wAZF1WzLUFAMy4BOwSH2jZmBoorMaE/RtZij6/ZcoFgrv7dH5/lA38Eh33zAfAjM+BR0cZz6Y2bqDwY0w4MB8AU04SvOyuq2zg4+h4aj4AzvIwha+qjN+66cLzMeGduQC4+eEy4zywr/U+K8t/hQX2xiJ/zQ/ACgdZ40vgtspKaNducCyOsdJXQO9fAbcOKGc5whofENzVd6jf3/YGTkTHccWFDMD6r4LT3MlOloHHCB4CblceYs3gDfxB4TeCcxReiwmr6hM3BYB6qHX1NGAA6tlqEKcGYJBa6znUANSz1SBODcAgtdZzqAGoZ6tBnBqAQWqt51ADUM9Wgzg1AIPUWs+hBqCerQZxagAGqbWeQw1APVsN4tQADFJrPYcagHq2GsTpf+KxwJB5Cd5mAAAAAElFTkSuQmCC");',"}",".ew-tree-table tr.ew-tree-table-open > td .ew-tree-icon-folder:after {",' background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAKwElEQVR4Xu2df9AVVRnHP899gUxmYKhsCpJREEeMakSoiGGCbIxSizIJ7i5OksZkMIxQjlOQyOCQ5o/8RWmkMdz7wjDC5I+hcFSKxEENh4YsEwPJAbVQ8AeQL733NPcKyn3v7r17d8/uvfvus//ec57n+3yf7z179uw5zwp6ZZoByXT0GjwqgIyLQAWgAsg4AxkPX0cAFUDGGch4+DoCqAAyzkDGw9cRQAWQcQYyHr6OACqA5hkw63kfr3IyOQZTIte8BUs9OnibEi/isEcEY8lqpswEHgHMGgbSxTyEyRjGIC1MfM8UGQ4CfyLHWp7jbllEKVNZjBBsIAGYAi7CrcCgCL6S6voM4IrDtqQcptlPQwGYAksRrkpVkIZD5JgmeR5IFe4WgK0rAFPkamBRC3BFd2k4AkwSl83RjfVeC74CMCuZSI6NqQ7d8G9KDJOLK3MEvTwY8BdAga0Io3sBa0vEYWEviCOWEDwFYDoZh+HxWDwmb/R18gzSx0Rv4r0FUORa4EfJ5yomj8IEyfNYTNZTbdZbAAU2IJyb6siOB2+4Qlx+3mvisRiInwC2I4yy6Ke1pgw/E5crWwuiPb373QL+BZzcnpBDobpLHGaF6tnLO6kAenmCG4WXFQH8WhwubURGFn/PhgAMD4nLl7KY4EYxZ0MAcBhhqOTZ14iQrP2eFQGU8/ogeb6qC0LVEs+SAMqRL+ctLpdZlRdFeoH32UBTpLc9Br6XbMMuhLUIm+jmzbZSQUdlV9M++rBTpnI4CWxZGwGS4NSWj2eBh4CbxGG3LaM97agA4mLWnt23gZ+yg8VxbHVTAdhLVNyWHqabKbb3NqgA4k6bTfuG+3GYYvNJRgVgM0FJ2DL8QFxutOVKBWCLyaTsGN6gH0NlKq/bcKkCsMFi0jYMs8XlDhtuVQA2WEzahuH34vJlG25VADZYTN7GPnE4yYZbFYANFlth4y362VjSVgG0Ink2fAon2Xi7qQKwkYxW2OglAtiP4QlgN8LLreAxtT4HcL1cwKGo+FsxAnQDv6HEbTKDv0QNQPtHYyBpAZSPm7mSp/ymS682YCA5ARiWMYS5Mon/tUHcCuEoA0kJ4AZx+KGy3n4MJCGA9eJwXqPQzSJyjGAMJU5s1FZ/r8NAH7roYIdM5T9BeIpXAIaXOMKZcgkH/MCYIp8GvgN8A/hQENDaJhADrwG/oy9X1BNDvAIQZkqee+okfwGGa9qq4FQgblPVaC85xsp09nqhjlMAO9nBCK9tTGYjfdhLJ3BRqqhMK1jDdoYw2msCHqcAypsZ53txZoqVo9pz08pnKnEbLhKXe3tij1MAk8VhQ0+HZjWj6GZ7KklMM2jD3eJW5lpVV5wC+IA47K8RQJEVwMVp5jKV2H3OR8YjAMPL4vLRmuSvoYMjvAoMTCWJ6Qa9Vhy+mdQIsEEcJtcIYCWjybE13TymFL2wVPK1dZ/iGgE8S7KYTi7F8KuUUphu2AlPAsu1eose9/9lwPfSzWRq0Q8Xh53J3AI6+IRM4681AiiwBeEzqaUwrcANh8Slvxf8OG4BXezg/T0XgCpr/afxX4S+aeUxtbgNfxCXSUkJYJs4nKXP/20ll5vFYV4yAjCsEJdve9z/y8/+5TUAvZJmwDBDXArJCADmicPNHgLQ5d+kE3/Mn+Hj4vK3ZARg+KK4POIxAdyEMKFVHGTWb/m7Cc9zgl9tgTgmgd5LwAUOIrrZI3EhGraIyzg/v7YFsFcchnhMAE+nm38kHrw6BMMycfl+MgLwObRoikwDVmk+WsCAcJnkWZ6MAOA6cWo/MGUKXI/optAWpB9KnC0zeDoZAQh5ydf+002BhxHOaQkBWXZqKHGQE+odIrU7BxBGSZ7yd/uqLlOsbArVV8DJi9FzUe54GDYF4L0EvIpTKLEr+djVIz67gOIRgOFpcTnb499f3u69VtPREgbmiMPt9TzbHAHuEYeZHgtASxB+3JLws+40x3iZXv/rb/YE4PNhJlNgPWKnnk3W89l0/APo3+gIuT0BwBfEqf3SqCnwCsKHmwavHaIy8Kw4jGxkxKYAapaAzSoGU2JPIxD6ewwMGDrFxWlk2Y4ADHvE5WMe9//zEf2Cd6MkxPJ7wIqidgQAnieATYGfIFwTS4BqtD4DwjmS59FGNNkRgM+WY1Pkt8DXGoHQ32NgoItB9U5lH/NoRwAwXRxWe6wB9N4vj8SQM4smXxCHU4PYsyOADs6Uafz9eIdmDQM54l8XIAg4bROagXXicGGQ3jYE4L0EXOBcpPZwaBBQ2iYiA4YF4la+AN/wsiGAP4vDWI8ngKsQljZEoA3iYOA8cVgfxHB0Afi8cDBF1mgBiCApiKGN8BHJ80oQy9EFAHPF4VaPCeDzwPAgILSNRQYML4nL4KAWowtAmCh5/lg1AXyAE3mDg0FBaDurDASqynbMY3QBQO0S8Eomkqt9L2A1TDXmx8AScVgYlJ6oAnhRHIZ6TADnI9wQFIS2s8rAheKwLqjFqAJ4UBwu8BBAESEfFIS2s8hAjlNlOi8EtRhNAIZrxWWBxwSwvCh0RlAQ2s4SA4YD4jKoGWvRBCB8S/KVx713L6MTwGb4t932UXGa230dTQAlzpAZ1Sd+TIHxCI/ZjkztBWKg6aLcUQTgtwQ8B6ldFwgEXxtFY8DnXEY9o+EFYHhK3Eqh56rLFCu1gWvqA0SLTHsHYkAY2ezHOMILAJaLw2UeAih/BuaTgQBrI3sM1KkDFM8IADV7zs2d9KV/pQ5Qzl5kaikQA4bHxWV8oLbHNYoyAnxeHDZVPQEUGIvwZLMgtL0VBm4XhznNWgovAI8956aTWRh+2SwIbW+BgQbfZvDzEFYAu8XhFI/7/53Ady2EoyaaZ+AscdjWbLdwAjDcL27tZk9T5ClgTLMgtH1EBhrUAYpjEljzxkkLQUZMYrTuW8UJ98cLOwLUfH3CrORT5JofgqLFrb2PMuD5SB6EnXACgNPFYUfVE0Anl5TPowdxqm2sM3C5OPwijNXmBeCz4GCK3AbMDgNC+0RkwDBOXLaEseIngOeAEZ4GDU+Iy2drngAKbEb4XBgQ2icCAwHqADU/CSzwJFK71fuoobvEYVbV8P9OJfA3tRBkhESG7/qMOIwK2917BCiwDuHrPiPAbHG5o0oAqxlJt3ct2rDAtF9ABnyKcwfsjd8tYDH4bCwUJki++n2/KVbOoXtWow4KRNuFZsDzXGZQa34jgP+xLq8l4CI3gnc9+qBAtF0IBgwH6MdgmcrhEL0rXbwFUP68WxevIQyoMmzYJS7DPCaAGxEmhgWh/UIyIMyXPDeF7O0vgPIvpsB1CFf2MH6fOEzxEIBWAo+ShXB915PnfBFMuO7v9PIcASoCWMEH6VNZ7Hlvl6lhsbhc3WMCOJxuysfA9EqKAUO5+P7MeiVgg0LxFUBFBEW+AtwH9DlqsObQgSlWvgBetTM4qHNt1zQD+zEs7PkU1rSV4zrUFcDRW0G50NMtwDBKjJAZ1f92U2ApUlshPAoo7fsuA12YCt+bgXvpxyMylW6b/DQUwDFnZiWn4fLPqPccm+DVVnQGAgsguiu10I4MqADaMSsJYlIBJEh2O7pSAbRjVhLEpAJIkOx2dKUCaMesJIhJBZAg2e3oSgXQjllJEJMKIEGy29GVCqAds5IgJhVAgmS3oysVQDtmJUFM/wdaDlOuM5Eu/AAAAABJRU5ErkJggg==");',"}",".ew-tree-table .ew-tree-icon-file:after {",' background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAJNUlEQVR4Xu2dXYxdVRXHf2tghhYaoba1Qk1owIwmfVBaTKRgQqMPlGjig2nDnDsF0whSnwqJ4SNoU2OLUSNPVDSx2t47hEkxaQMBI1hB/EiE6osYqjGUYPGjCihN6Uy525wzt7UdZu7ZZ87a5949Z52XeVl77bX//9/d52vvM4IdtVZAaj16GzwGQM0hMAAMgJorUPPh2wxgANRcgZoP32YAA6DmCtR8+DYDGADVKuB2s4BB1gMbEYZxLEFYDlxQbSU97+0Ejn8hHMPxR4R9LOZxuZGTVVZW2QzgxlnGBNuBUYSLqhxkNH05jgN7GeIrsoF/VlF3cADcQc7nKHfiuM+M97Q0BUH4GpfxbVnHKc9WcwoLCoBrsRjHYwhr51Rd3Rs5foXwaUl4PZQUwQBwLa4AngZWhiq+JnlfBj4pCX8JMd4gALgxluJ4Hrg8RNE1zHkE4WoZ4Zj22NUBcOMsZILnEFZrF1vrfI5DDHGdbOCEpg76ADTZiXCXZpGWq6OAsFNGuEdTD1UA3B7exwDpdLUgt0jHqwjjwH6EF0NMb7k19DAgO03CKtp8pvNM5AO55TjeZoCVMsLfc2M9A3QBaPEQcGtO328hbOYw+2Qbbc8653WY28YAw3yONrsRLswZ7Pck4TYtQdQAcOMMMckbwMIuxaVPua6VhBe0BjCf8rgWa4Bf5jwVPcEgl8gGJjTGrgfAGDfgeCKnqC2SsEuj8Pmaw7W4HXiw6/iE9TLCkxoa6AHQyopOi5/5cLzCCq4M/WRLQ5Re5ug8Of1z11tox3el0UXrAgPQA6DJQYTru/R9ryTsKFBbbUNdK7vS/3qXH9PPpcE6DYH0AGjxEjA8a1Ft1sgohzSKnu853MNcRburVocl4UMaOugB0MxeYMx+BTt14fKmRtHzPYcb5+LOBfVsp9Pj0mCRhg56ALRw3QqSxPYgFDHMVaSnAVDElQpjDYAKxe7HrgyAfnSlwpoMgArF7seuDIB+dKXCmgyACsXux64MgH50pcKaDIAKxe7HrgyAfnSlwpoMgBnEduO8n0m+j+MahCUV+pHf1dQun18zyBdkA3/Lb9A9wgCYpk9nj8EfEC4tK27Q9o7XGOIjZXf2GADTAWjyQ4Sbg5qnl3yvJGwqk84AePcMkO6VSxdSxnAck4RlZQo1AN4NwF+By8qIWmHbo5Kwokx/BkDcp4A9kpQ7XRkA0wGY2nPw+yguAoVVZTd0GgAz3Qbu5VIGsr0H1wLvLTPFBmj772xJd5vbZJTXyuY3AMoqGHl7AyByA8uWbwCUVTDy9gZA5AaWLd8AKKtg5O0NgMgNLFu+AVBWwcjbGwCRG1i2fAOgrIKRtzcAIjewbPkGQFkFI29vAERuYNnyDYCZXgbZmsAzqmjtto5md7CtCTz3F1E/AGxN4DkE1A+AVvb9fFsT2MGgjgDYmsCz5oD6ARDXKcDWBE6/iC9LbOc7xLYmsK6ngHTcztYE1vc2sOyDldja24Og2BxTrtcAUBY0tnQGQGyOKddrACgLGls6AyA2x5TrNQCUBY0tnQEQm2PK9RoAyoLGls4AiM0x5XoNAGVBY0tnAMTmmHK9BsAMgqp+J1D5u37K/mMATFM02JpApe/6GQCB/8eNC7sgpPR3/QyA0ACEXRNY+rt+BkB4AEKuCSz9XT8DIDQAYU8BpdfwGQChAQj1ncD0IlDhu34GQGAAUoGV1wSqftfPAKgAAG2RQ+Rzu1nAIOuBjQjDOJYgLAcu0Oyv7Crr07VEszdQU7wQudw4y5hgOzCKcFGIPs7OaQCEVtgzvzvI+RzlThz3VWF8p6wJSXRmFJsBPI2eKazzdPIxhLUl0syl6RFJWDmXhtPbGABzVNG1uAJ4GnSMKFSG4zfS4JpCbWYJNgDmoKIbYymO54HL59C8fBPHj6TBLeUTgQFQUEU3zkImeA5hdcGmeuHCRhlhXCOhAVBQRddkJ8JdBZtphr/DIEtkA29qJDUACqjY2aF8BGFBbjPHq0j2K92P8KKMcKxbGzfGKhy/ABbn5N4vCZ/N7d8zwADwFCoNc63sv5XcmtPkLYTNHGafbKPtk76A+dDmwzLKSz55fWIMAB+VUvPHGWKSN4CFXZqcTP+djSS84JmWQuY7xqRB4pvbJ84A8FEpBWCMG3A8kRO+RRJ2eaZMZ5SPAj/zmPbTlEd5h6tkE//wze8TZwD4qDQ1/T8I3D5ruOMVVnClrOOUT8rMfMczCO/JjXdM4vi4jHIoN7ZggAHgKZhrchDh+i7h90rCDp90hcwHB9wiCXt8cheNMQA8FXOt7MJreNbwNmt8fqEFzU/t3ywNfuBZZuEwA8BTMtfkOMKFs4YPcknevblr8jHgKa9pf6qjQtcUnkM5J8wA8FSt7Dr9zHzJLvgWeXYZ3Py0DgPA040yABQ237FVGjzgWVqpME0A/tuVbsfF0uA/partYeO5AtDP5uvOAE3+hPDBWT0aYLXcxO966GGprucCQL+brw3AswifmFVlxz3SYGcpF3rYuCgA7mHW0uYn3ud8x93S4P6qh6h3CmiyC+GLXQAo9KCkaiHy+isCQMf8p3IeG/+/yx6ZrzsDtLgReLyrkI4vSSN7ohbd4QvAHMzfLg2+2itB9GaA9GXJBK93vVeGk7RZ6/PApFeCzNavDwCuxaeAAwV++fdLg7t7OVY1ANJBeL8udXyehEdFssecURx5AAB3AN8EzvMakOMBabDVKzZgkC4AYyynzcveCybgEYQDPgsmAmrgldoDAK88WVCfmK96DXB69K7JNxC+7K9GzSL7yPwwAKSLJid5Fri6Ztb6DHeXJGzxCawqRvUUcGYWmFo2/duerJmvSrni/fSd+UFmgDMQTG2c+Clkf+t+fEeS7CKx744gM8BZEKQrXNPbouv6buTVFHQSx83S4JFquiveS1AAsgvehxhkEXdUvHmyuBL6LZ5hgK39/v4jOABnZoN0+/QkO3DcVOEuWn1bu2V0vA38mPP4Vr8bf3oYlQFwFgjpXcJ6HBshe3u4NMQHFII7ny7UlOy/maYbPtI3oY9yigOyiePB+1bsoHIAFGu3VAoKGAAKIsacwgCI2T2F2g0ABRFjTmEAxOyeQu0GgIKIMacwAGJ2T6F2A0BBxJhTGAAxu6dQuwGgIGLMKf4HAR/hrhUhGSQAAAAASUVORK5CYII=");',"}","</style>"].join(""));s("treeTable",a)});
\ No newline at end of file
/**
*
* @name: 子表格扩展
* @author: yelog
* @link: https://github.com/yelog/layui-soul-table
* @license: MIT
* @version: v1.6.2
*/
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);
});
This diff could not be displayed because it is too large.
/**
*
* @name: 子表格扩展
* @author: yelog
* @link: https://github.com/yelog/layui-soul-table
* @license: MIT
* @version: v1.6.2
*/
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);
});
......@@ -16,7 +16,8 @@ layui.config({ // common.js是配置layui扩展模块的目录,每个页面
citypicker: 'city-picker/city-picker',
introJs: 'introJs/introJs',
zTree: 'zTree/zTree',
xmSelect: 'xmSelect/xm-select'
xmSelect: 'xmSelect/xm-select',
soulTable: 'soulTable'
}).use(['layer', 'admin'], function () {
var $ = layui.jquery;
var layer = layui.layer;
......
<script>
layui.use(['table', 'form', 'element', 'table', 'layer', 'admin'], function () {
let table = layui.table
table.render({
elem: '#list'
, url: '/api/chain/GetChainCheckList'
, method: 'post'
, size: 'sm'
, limit: 20
, cellMinWidth: 80 //全局定义常规单元格的最小宽度
, where: {}
, loading: true
, first: true //不显示首页
, last: false //不显示尾页
, cols: [[
{
field: 'status_name', title: '跟进结果', align: 'center',
},
{field: 'check_content', title: '跟进内容', align: 'center'},
{field: 'create_time', title: '跟进时间', width: 150, align: 'center'},
{field: 'create_name', title: '跟进人', width: 150, align: 'center'},
]]
, id: 'list'
, page: {}
});
});
</script>
<script>
layui.use(['table', 'form', 'element', 'upload', 'layer', 'Split', 'admin', 'xmSelect'], function () {
layui.use(['table', 'form', 'element', 'upload', 'layer', 'Split', 'soulTable', 'admin', 'xmSelect'], function () {
let $ = layui.jquery;
let Split = layui.Split;
let table = layui.table;
......@@ -10,6 +10,8 @@
let initCondition = {source_type: 'all'};
let whereCondition = initCondition;
let type = 'all';
var soulTable = layui.soulTable;
//监听复选框事件,被选中的行高亮显示
table.on('checkbox(chainList)', function (obj) {
......@@ -17,8 +19,47 @@
});
let cols = [
{type: 'checkbox', fixed: true},
{field: 'chain_id', title: '序号', align: 'center', width: 80},
{field: 'com_name', title: '公司名称', align: 'center', width: 250},
{field: 'is_entity_name', title: '实体名单', align: 'center', width: 100},
{field: 'check_status_name', title: '跟进结果', align: 'center', width: 100},
{
field: 'chain_check',
title: '跟进记录',
align: 'center',
width: 100,
childTitle: '跟进记录',
show: 2,
layerOption: {title: '跟进记录', area: '1000px',},
children: [
{
title: '子表',
height: 300,
data: function (row) {
return row.sub;
},
size: 'sm',
page: true,
cols: [[
{field: 'check_status_name', title: '跟进结果', width: 100},
{field: 'check_time', title: '跟进时间', width: 150},
{field: 'check_content', title: '跟进内容'},
{field: 'check_name', title: '跟进人', width: 150},
]],
toolEvent: function (obj, pobj) {
},
}
],
templet: function () {
return '<span style="color: dodgerblue" class="view_check">查看记录</span>';
},
},
{
field: 'has_supplier', title: '是否建档', align: 'center', width: 100, templet: function (data) {
return data.supplier && data.com_name ? '是' : '否';
}
},
{field: 'company_nature', title: '公司性质', align: 'center', width: 100},
{field: 'region', title: '所在区域', align: 'center', width: 100},
{field: 'link_name', title: '联系人', align: 'center', width: 170},
......@@ -73,10 +114,18 @@
, id: 'chainList'
, page: {}
, done: function (res, curr, count) {
soulTable.render(this);
currentPage = curr;
}
});
$(function () {
$('.view_check').click(function () {
alert(123);
$(this).prev().click();
});
});
form.on('submit(load)', function (data) {
whereCondition = $.extend(false, initCondition, data.field);
......@@ -133,6 +182,29 @@
}
}
});
//审批供应商弹窗
$("#checkStatus").click(function () {
let checkStatus = table.checkStatus('chainList');
let data = checkStatus.data;
if (!data.length) {
layer.msg('请先选择要操作的供应商', {icon: 5})
} else {
if (data.length > 1) {
layer.msg('该操作不支持多选', {icon: 5})
return;
}
let chainId = data[0].chain_id;
let status = data[0].status;
layer.open({
type: 2,
content: '/chain/CheckChain?view=iframe&chain_id=' + chainId,
area: ['800px', '65%'],
title: '跟进情况',
end: function () {
table.reload('chainList');
}
});
}
})
});
</script>
<script>
layui.use(['table', 'form', 'element', 'layer', 'admin'], function () {
let admin = layui.admin;
let form = layui.form;
let element = layui.element;
form.on('submit(checkChain)', function (data) {
admin.showLoading({type: 3});
let chainId = getQueryVariable('chain_id');
let url = '/api/chain/checkChain?chain_id=' + chainId;
$.ajax({
url: url,
type: 'post',
data: data.field,
dataType: 'json',
timeout: 20000,
success: function (res) {
if (!res) return layer.msg('网络错误,请重试', {icon: 5});
if (res.err_code === 0) {
admin.removeLoading();
admin.closeThisDialog();
parent.layer.msg(res.err_msg, {icon: 6});
} else {
admin.removeLoading();
parent.layer.msg(res.err_msg, {icon: 5});
}
},
error: function () {
admin.removeLoading();
return layer.msg('网络错误,请重试', {icon: 5});
}
});
return false;
});
form.on('submit(cancel)', function (data) {
admin.closeThisDialog();
});
});
</script>
<blockquote class="layui-elem-quote layui-text">
<b>审核列表 : </b> (只要申请部门或者被申请部门和你是同一个部门的,具有审核权限的你都可以看到申请)
</blockquote>
<table class="layui-table" id="list" lay-filter="list"></table>
<script type="text/html" id="operate">
<div>
<button type="button" value="@{{ d.id}}" status="pass" class="layui-btn layui-btn-xs audit_supplier_share_apply" lay-event="pass">同意
</button>
<button type="button" value="@{{ d.id}}" status="reject" class="layui-btn layui-btn-xs layui-btn-danger audit_supplier_share_apply" lay-event="reject">拒绝
</button>
</div>
</script>
......@@ -31,6 +31,18 @@
@inject('statusPresenter','App\Presenters\StatusPresenter')
{!! $statusPresenter->render('supplier_type','入驻类型',request()->get('data_type'),config('field.ChainSupplierType')) !!}
</div>
<div class="layui-inline">
@inject('statusPresenter','App\Presenters\StatusPresenter')
{!! $statusPresenter->render('is_entity','实体名单',request()->get('is_entity'),config('field.IsEntity')) !!}
</div>
<div class="layui-inline">
@inject('statusPresenter','App\Presenters\StatusPresenter')
{!! $statusPresenter->render('has_supplier','是否建档',request()->get('has_supplier'),[1=>'是',-1=>'否']) !!}
</div>
<div class="layui-inline">
@inject('statusPresenter','App\Presenters\StatusPresenter')
{!! $statusPresenter->render('check_status','跟进结果',request()->get('check_status'),config('field.ChainCheckStatus')) !!}
</div>
</div>
<div class="layui-row">
<div class="layui-inline" style="width: 600px">
......@@ -50,7 +62,7 @@
</div>
<div style="margin-left: 20px;margin-right: 20px">
<div class="layui-btn-group demoTable" style="margin-top: 15px">
<button type="button" class="layui-btn layui-btn-sm layui-btn" lay-filter="checkStatus" id="checkStatus">跟进情况</button>
</div>
<table class="layui-table" id="chainList" lay-filter="chainList"></table>
</div>
<style>
.layui-form-item {
margin-bottom: 5px;
}
</style>
<div class="layui-card">
<div class="layui-card-body">
<form class="layui-form" action="">
<div class="layui-form-item">
<label class="layui-form-label"><span style="color: red">*</span>跟进结果 : </label>
<div class="layui-input-block">
<input type="radio" name="status" value="1" title="渠道已跟进">
<input type="radio" name="status" value="2" title="采购已通过">
<input type="radio" name="status" value="3" title="采购未通过">
<input type="radio" name="status" value="4" title="采购未反馈">
</div>
</div>
<div class="layui-form-item layui-form-text">
<label class="layui-form-label"><span style="color: red">*</span>跟进内容 : </label>
<div class="layui-input-block">
<textarea name="check_content" placeholder="" class="layui-textarea"></textarea>
</div>
</div>
<div class="layui-form-item">
<div align="center" style="margin-top: 20px;text-align: right">
<button type="button" class="layui-btn layui-btn-sm layui-btn-info submit-loading" lay-submit
lay-filter="checkChain">确定
</button>
<button type="button" class="layui-btn layui-btn-sm layui-btn-primary" lay-submit
lay-filter="cancel">取消
</button>
</div>
</div>
</form>
</div>
</div>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment