soulTable.js 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248
  1. /**
  2. *
  3. * @name: 表格增强插件
  4. * @author: yelog
  5. * @version: v1.4.4
  6. */
  7. layui.define(['table', 'tableFilter', 'tableChild', 'tableMerge'], function (exports) {
  8. var tableFilter = layui.tableFilter,
  9. tableChild = layui.tableChild,
  10. tableMerge = layui.tableMerge,
  11. $ = layui.$,
  12. table = layui.table,
  13. HIDE = 'layui-hide',
  14. isFirst = true; // 第一次加载表格
  15. // 封装方法
  16. var mod = {
  17. render: function (myTable) {
  18. var curTableSession = localStorage.getItem(location.pathname + location.hash + myTable.id);
  19. if (myTable.filter && myTable.filter.cache && isFirst && curTableSession) {
  20. myTable.cols = this.deepParse(curTableSession);
  21. isFirst = false;
  22. table.reload(myTable.id, myTable)
  23. } else {
  24. tableFilter.render(myTable);
  25. tableChild.render(myTable);
  26. tableMerge.render(myTable);
  27. // 修复合计栏固定列问题
  28. if (myTable.fixTotal) {
  29. this.fixTotal(myTable)
  30. }
  31. if (typeof myTable.drag === 'undefined' || myTable.drag) {
  32. this.drag(myTable);
  33. }
  34. if (myTable.rowDrag) {
  35. this.rowDrag(myTable)
  36. }
  37. this.autoColumnWidth(myTable)
  38. this.contextmenu(myTable);
  39. if (typeof myTable.fixResize === 'undefined' || myTable.fixResize) {
  40. this.fixResizeRightFixed(myTable);
  41. }
  42. if (myTable.overflow) {
  43. this.overflow(myTable);
  44. }
  45. this.fixFixedScroll(myTable);
  46. }
  47. }
  48. /**
  49. * excel表格导出
  50. * @param myTable
  51. * @param curExcel
  52. * @param customizeConfig 具体配置参考 tableFilter 中的 export 的 customizeConfig 配置
  53. */
  54. , export: function (myTable, curExcel, customizeConfig) {
  55. tableFilter.export(myTable.config || myTable, curExcel, customizeConfig);
  56. }
  57. , getCssRule: function (that, key, callback) {
  58. var style = that.elem.next().find('style')[0]
  59. , sheet = style.sheet || style.styleSheet || {}
  60. , rules = sheet.cssRules || sheet.rules;
  61. layui.each(rules, function (i, item) {
  62. if (item.selectorText === ('.laytable-cell-' + key)) {
  63. return callback(item), true;
  64. }
  65. });
  66. }
  67. , autoColumnWidth: function (myTable) {
  68. var _this = this,
  69. $table = $(myTable.elem),
  70. th = $table.next().children('.layui-table-box').children('.layui-table-header').children('table').children('thead').children('tr').children('th'),
  71. fixTh = $table.next().children('.layui-table-box').children('.layui-table-fixed').children('.layui-table-header').children('table').children('thead').children('tr').children('th'),
  72. $tableBodytr = $table.next().children('.layui-table-box').children('.layui-table-body').children('table').children('tbody').children('tr');
  73. String.prototype.width = function (font) {
  74. var f = font || $('body').css('font'),
  75. o = $('<div>' + this + '</div>')
  76. .css({
  77. 'position': 'absolute',
  78. 'float': 'left',
  79. 'white-space': 'nowrap',
  80. 'visibility': 'hidden',
  81. 'font': f
  82. })
  83. .appendTo($('body')),
  84. w = o.width();
  85. o.remove();
  86. return w;
  87. }
  88. th.add(fixTh).on('dblclick', function (e) {
  89. var othis = $(this)
  90. , field = othis.data('field')
  91. , key = othis.data('key')
  92. , oLeft = othis.offset().left
  93. , pLeft = e.clientX - oLeft;
  94. if (othis.attr('colspan') > 1) {
  95. return;
  96. }
  97. if ($(this).parents('.layui-table-fixed-r').length > 0 ? pLeft <= 10 : othis.width() - pLeft <= 10) {
  98. var maxWidth = othis.text().width(othis.css('font')) + 21, font = othis.css('font');
  99. $tableBodytr.children('td[data-field="' + field + '"]').each(function (index, elem) {
  100. var curWidth = $(this).text().width(font);
  101. if (maxWidth < curWidth) {
  102. maxWidth = curWidth
  103. }
  104. })
  105. maxWidth += 32;
  106. _this.getCssRule(myTable, key, function (item) {
  107. item.style.width = maxWidth + 'px'
  108. });
  109. for (var i = 0; i < myTable.cols.length; i++) {
  110. for (var j = 0; j < myTable.cols[i].length; j++) {
  111. if (myTable.cols[i][j].field === field) {
  112. myTable.cols[i][j].width = maxWidth;
  113. break;
  114. }
  115. }
  116. }
  117. }
  118. })
  119. }
  120. /**
  121. * 左右拖拽调整列顺序、向上拖隐藏列
  122. * @param myTable
  123. */
  124. , drag: function (myTable) {
  125. if (myTable.cols.length > 1) {
  126. // 如果是复杂表头,则自动禁用拖动效果
  127. return;
  128. }
  129. var _this = this,
  130. $table = $(myTable.elem),
  131. $tableBox = $table.next().children('.layui-table-box'),
  132. $tableHead = $.merge($tableBox.children('.layui-table-header').children('table'), $tableBox.children('.layui-table-fixed').children('.layui-table-header').children('table')),
  133. $fixedBody = $tableBox.children('.layui-table-fixed').children('.layui-table-body').children('table'),
  134. $noFixedBody = $tableBox.children('.layui-table-body').children('table'),
  135. $tableBody = $.merge($tableBox.children('.layui-table-body').children('table'), $fixedBody),
  136. $totalTable = $table.next().children('.layui-table-total').children('table'),
  137. $fixedTotalTable = $table.next().children('.layui-table-total').children('table.layui-table-total-fixed'),
  138. $noFixedTotalTable = $table.next().children('.layui-table-total').children('table:eq(0)'),
  139. tableId = myTable.id,
  140. isSimple = myTable.drag === 'simple' || (myTable.drag && myTable.drag.type === 'simple'), // 是否为简易拖拽
  141. toolbar = myTable.drag && myTable.drag.toolbar, // 是否开启工具栏
  142. isDraging = false, isStart = false;
  143. if (!$tableHead.attr('drag')) {
  144. $tableHead.attr('drag', true);
  145. if (toolbar) {
  146. $tableBox.append('<div class="soul-drag-bar"><div data-type="left">左固定</div><div data-type="none">不固定</div><div data-type="right">右固定</div></div>')
  147. var $dragBar = $tableBox.children('.soul-drag-bar');
  148. $dragBar.children('div').on('mouseenter', function () {
  149. $(this).addClass('active')
  150. }).on('mouseleave', function () {
  151. $(this).removeClass('active')
  152. })
  153. }
  154. $tableHead.find('th').each(function () {
  155. var $this = $(this),
  156. field = $this.data('field'),
  157. key = $this.data('key');
  158. if (!key) {
  159. return;
  160. }
  161. var keyArray = key.split('-'),
  162. curColumn = myTable.cols[keyArray[1]][keyArray[2]],
  163. curKey = keyArray[1] + '-' + keyArray[2],
  164. isInFixed = $this.parents('.layui-table-fixed').length > 0;
  165. // 绑定鼠标按下事件
  166. $(this).find('span:first,.laytable-cell-checkbox')
  167. .css('cursor', 'move')
  168. .on('mousedown', function (e) {
  169. if (e.button !== 0) {
  170. return;
  171. }
  172. e.preventDefault();
  173. var $cloneHead = $this.clone().css('visibility', 'hidden'),
  174. originLeft = $this.position().left,
  175. originTop = $this.offset().top,
  176. disX = e.clientX - originLeft, // 鼠标距离被移动元素左侧的距离
  177. color = $this.parents('tr:eq(0)').css("background-color"),
  178. width = $this.width(), moveDistince = 0,
  179. $that = $(this),
  180. isFixed = curColumn.fixed;
  181. isStart = true;
  182. //区分click、drag事件
  183. // 阻止文本选中
  184. $(document).bind("selectstart", function () {
  185. return false;
  186. });
  187. // 移动事件
  188. $('body').on('mousemove', function (e) {
  189. if (isStart && $cloneHead) {
  190. $tableBox.removeClass('no-left-border');
  191. if (!isDraging) {
  192. if (toolbar) {
  193. $dragBar.attr('data-type', isFixed || 'none')
  194. $dragBar.addClass('active')
  195. }
  196. $this.after($cloneHead);
  197. $this.addClass('isDrag').css({
  198. 'position': 'absolute',
  199. 'z-index': 1,
  200. 'border-left': '1px solid #e6e6e6',
  201. 'background-color': color,
  202. 'width': width + 1
  203. });
  204. if (isSimple) {
  205. //设置蒙板
  206. } else {
  207. (isInFixed ? $fixedBody : $tableBody).find('td[data-key="' + key + '"]').each(function () {
  208. $(this).after($(this).clone().css('visibility', 'hidden').attr('data-clone', ''));
  209. $(this).addClass('isDrag').css({
  210. 'position': 'absolute',
  211. 'z-index': 1,
  212. 'border-left': '1px solid #e6e6e6',
  213. 'background-color': $(this).css('background-color'),
  214. 'width': width + 1
  215. });
  216. })
  217. if ($totalTable.length > 0) {
  218. (isInFixed ? $fixedTotalTable : $totalTable).find('td[data-key="' + key + '"]').each(function () {
  219. $(this).after($(this).clone().css('visibility', 'hidden').attr('data-clone', ''));
  220. $(this).addClass('isDrag').css({
  221. 'position': 'absolute',
  222. 'z-index': 1,
  223. 'background-color': $(this).parents('tr:eq(0)').css('background-color'),
  224. 'width': width + 1
  225. });
  226. })
  227. }
  228. }
  229. }
  230. isDraging = true;
  231. var x, y, i, j, tempCols,
  232. left = e.clientX - disX, // 计算当前被移动列左侧位置应该哪里
  233. $leftTh = $cloneHead.prev().prev(),
  234. hasLeftTh = $leftTh.length > 0,
  235. leftKey = hasLeftTh ? $leftTh.data('key').split('-') : [],
  236. $rightTh = $cloneHead.next().hasClass('layui-table-patch') ? [] : $cloneHead.next(),
  237. hasRightTh = $rightTh.length > 0,
  238. rightKey = hasRightTh ? $rightTh.data('key').split('-') : [],
  239. leftMove = hasLeftTh && ($cloneHead.position().left - left > $leftTh.width() / 2.0),
  240. rightMove = hasRightTh && (left - $cloneHead.position().left > $rightTh.width() / 2.0);
  241. moveDistince = Math.abs($cloneHead.position().left - left); //记录移动距离
  242. // 移动到左右两端、checbox/radio 固定列等停止移动
  243. if ($cloneHead.position().left - left > 0
  244. ? !hasLeftTh || !!isFixed !== !!myTable.cols[leftKey[1]][leftKey[2]].fixed
  245. : !hasRightTh || !!isFixed !== !!myTable.cols[rightKey[1]][rightKey[2]].fixed) {
  246. $this.css('left', $cloneHead.position().left);
  247. $tableBody.find('td[data-key="' + key + '"][data-clone]').each(function (e) {
  248. $(this).prev().css('left', $cloneHead.position().left);
  249. })
  250. if ($totalTable.length > 0) {
  251. $totalTable.find('td[data-key="' + key + '"][data-clone]').each(function (e) {
  252. $(this).prev().css('left', $cloneHead.position().left);
  253. })
  254. }
  255. $tableBox.addClass('no-left-border');
  256. return;
  257. }
  258. $this.css('left', left);
  259. if (leftMove) {
  260. $cloneHead.after($leftTh);
  261. // 更新隐藏列顺序
  262. $('#soul-columns' + tableId + '>li[data-value=' + field + ']').after($('#soul-columns' + tableId + '>li[data-value=' + field + ']').prev())
  263. // 更新配置信息
  264. for (i = 0; i < myTable.cols.length; i++) {
  265. for (j = 0; j < myTable.cols[i].length; j++) {
  266. if (myTable.cols[i][j].key === curKey) {
  267. x = i;
  268. y = j;
  269. break;
  270. }
  271. }
  272. if (typeof x !== 'undefined' && typeof y !== 'undefined') {
  273. break;
  274. }
  275. }
  276. tempCols = myTable.cols[x][y - 1];
  277. myTable.cols[x][y - 1] = myTable.cols[x][y];
  278. myTable.cols[x][y] = tempCols;
  279. if (myTable.filter && myTable.filter.cache) {
  280. localStorage.setItem(location.pathname + location.hash + myTable.id, _this.deepStringify(myTable.cols))
  281. }
  282. } else if (rightMove) {
  283. $cloneHead.prev().before($rightTh);
  284. // 更新隐藏列顺序
  285. $('#soul-columns' + tableId + '>li[data-value=' + field + ']').before($('#soul-columns' + tableId + '>li[data-value=' + field + ']').next())
  286. // 更新配置信息
  287. for (i = 0; i < myTable.cols.length; i++) {
  288. for (j = 0; j < myTable.cols[i].length; j++) {
  289. if (myTable.cols[i][j].key === curKey) {
  290. x = i;
  291. y = j;
  292. break;
  293. }
  294. }
  295. if (typeof x !== 'undefined' && typeof y !== 'undefined') {
  296. break;
  297. }
  298. }
  299. tempCols = myTable.cols[x][y + 1];
  300. myTable.cols[x][y + 1] = myTable.cols[x][y];
  301. myTable.cols[x][y] = tempCols;
  302. if (myTable.filter && myTable.filter.cache) {
  303. localStorage.setItem(location.pathname + location.hash + myTable.id, _this.deepStringify(myTable.cols))
  304. }
  305. }
  306. $tableBody.find('td[data-key="' + key + '"][data-clone]').each(function () {
  307. $(this).prev().css('left', left);
  308. if (leftMove) {
  309. if ($(this).prev().prev().length !== 0) {
  310. $(this).after($(this).prev().prev());
  311. }
  312. } else if (rightMove) {
  313. if ($(this).next().length !== 0) {
  314. $(this).prev().before($(this).next());
  315. }
  316. }
  317. })
  318. if ($totalTable.length > 0) {
  319. $totalTable.find('td[data-key="' + key + '"][data-clone]').each(function () {
  320. $(this).prev().css('left', left);
  321. if (leftMove) {
  322. if ($(this).prev().prev().length !== 0) {
  323. $(this).after($(this).prev().prev());
  324. }
  325. } else if (rightMove) {
  326. if ($(this).next().length !== 0) {
  327. $(this).prev().before($(this).next());
  328. }
  329. }
  330. })
  331. }
  332. /* 拖动隐藏列 */
  333. if (e.clientY - originTop < -15) {
  334. if ($('#column-remove').length === 0) {
  335. $('body').append('<i id="column-remove" class="layui-red layui-icon layui-icon-delete"></i>')
  336. }
  337. $('#column-remove').css({
  338. top: e.clientY - $('#column-remove').height() / 2,
  339. left: e.clientX - $('#column-remove').width() / 2,
  340. 'font-size': (originTop - e.clientY) + 'px'
  341. })
  342. $('#column-remove').show();
  343. } else {
  344. $('#column-remove').hide();
  345. }
  346. }
  347. }).on('mouseup', function () {
  348. $(document).unbind("selectstart");
  349. $('body').off('mousemove').off('mouseup')
  350. if (isStart && $cloneHead) {
  351. isStart = false;
  352. if (isDraging) {
  353. if (curColumn.type !== 'checkbox') {
  354. $that.on('click', function (e) {
  355. e.stopPropagation();
  356. });
  357. }
  358. isDraging = false;
  359. $tableBox.removeClass('no-left-border')
  360. $this.removeClass('isDrag').css({
  361. 'position': 'relative',
  362. 'z-index': 'inherit',
  363. 'left': 'inherit',
  364. 'border-left': 'inherit',
  365. 'width': 'inherit',
  366. 'background-color': 'inherit'
  367. });
  368. $this.next().remove();
  369. var prefKey = $this.prev().data('key');
  370. if (isFixed) {
  371. var $noFixedTh = $tableBox.children('.layui-table-header').children('table').find('th[data-key="' + key + '"]');
  372. if (prefKey) {
  373. $noFixedTh.parent().children('th[data-key="' + prefKey + '"]').after($noFixedTh)
  374. } else {
  375. if (isFixed === 'right') {
  376. if ($this.siblings().length > 0) {
  377. $tableBox.children('.layui-table-header').children('table').find('th[data-key="' + $this.next().data('key') + '"]').prev().after($noFixedTh);
  378. }
  379. } else {
  380. $noFixedTh.parent().prepend('<th class="layui-hide"></th>');
  381. $noFixedTh.parent().children('th:first').after($noFixedTh);
  382. $noFixedTh.parent().children('th:first').remove();
  383. }
  384. }
  385. }
  386. if (isSimple) {
  387. $tableBody.find('td[data-key="' + key + '"]').each(function () {
  388. if (prefKey) {
  389. $(this).parent().children('td[data-key="' + prefKey + '"]').after($(this))
  390. } else {
  391. if (isFixed === 'right') {
  392. if ($this.siblings().length > 0) {
  393. var $preTd = $(this).parent().children('td[data-key="' + $this.next().data('key') + '"]').prev();
  394. if ($preTd.length > 0) {
  395. $preTd.after($(this));
  396. } else {
  397. $(this).parent().prepend('<td class="layui-hide"></td>');
  398. $(this).parent().children('td:first').after($(this));
  399. $(this).parent().children('td:first').remove();
  400. }
  401. }
  402. } else {
  403. $(this).parent().prepend('<td class="layui-hide"></td>');
  404. $(this).parent().children('td:first').after($(this));
  405. $(this).parent().children('td:first').remove();
  406. }
  407. }
  408. });
  409. if ($totalTable.length > 0) {
  410. $totalTable.find('td[data-key="' + key + '"]').each(function () {
  411. if (prefKey) {
  412. $(this).parent().children('td[data-key="' + prefKey + '"]').after($(this))
  413. } else {
  414. if (isFixed === 'right') {
  415. var $preTd = $(this).parent().children('td[data-key="' + $this.next().data('key') + '"]').prev();
  416. if ($preTd.length > 0) {
  417. $preTd.after($(this));
  418. } else {
  419. $(this).parent().prepend('<td class="layui-hide"></td>');
  420. $(this).parent().children('td:first').after($(this));
  421. $(this).parent().children('td:first').remove();
  422. }
  423. } else {
  424. $(this).parent().prepend('<td class="layui-hide"></td>');
  425. $(this).parent().children('td:first').after($(this));
  426. $(this).parent().children('td:first').remove();
  427. }
  428. }
  429. });
  430. }
  431. } else if (isInFixed) {
  432. $noFixedBody.find('td[data-key="' + key + '"]').each(function () {
  433. if (prefKey) {
  434. $(this).parent().children('td[data-key="' + prefKey + '"]').after($(this))
  435. } else {
  436. if (isFixed === 'right') {
  437. if ($this.siblings().length > 0) {
  438. var $preTd = $(this).parent().children('td[data-key="' + $this.next().data('key') + '"]').prev();
  439. if ($preTd.length > 0) {
  440. $preTd.after($(this));
  441. } else {
  442. $(this).parent().prepend('<td class="layui-hide"></td>');
  443. $(this).parent().children('td:first').after($(this));
  444. $(this).parent().children('td:first').remove();
  445. }
  446. }
  447. } else {
  448. $(this).parent().prepend('<td class="layui-hide"></td>');
  449. $(this).parent().children('td:first').after($(this));
  450. $(this).parent().children('td:first').remove();
  451. }
  452. }
  453. });
  454. $fixedBody.find('td[data-key="' + key + '"][data-clone]').each(function () {
  455. $(this).prev().removeClass('isDrag').css({
  456. 'position': 'relative',
  457. 'z-index': 'inherit',
  458. 'left': 'inherit',
  459. 'border-left': 'inherit',
  460. 'width': 'inherit',
  461. 'background-color': 'inherit'
  462. });
  463. $(this).remove();
  464. });
  465. if ($totalTable.length > 0) {
  466. $noFixedTotalTable.find('td[data-key="' + key + '"]').each(function () {
  467. if (prefKey) {
  468. $(this).parent().children('td[data-key="' + prefKey + '"]').after($(this))
  469. } else {
  470. if (isFixed === 'right') {
  471. var $preTd = $(this).parent().children('td[data-key="' + $this.next().data('key') + '"]').prev();
  472. if ($preTd.length > 0) {
  473. $preTd.after($(this));
  474. } else {
  475. $(this).parent().prepend('<td class="layui-hide"></td>');
  476. $(this).parent().children('td:first').after($(this));
  477. $(this).parent().children('td:first').remove();
  478. }
  479. } else {
  480. $(this).parent().prepend('<td class="layui-hide"></td>');
  481. $(this).parent().children('td:first').after($(this));
  482. $(this).parent().children('td:first').remove();
  483. }
  484. }
  485. });
  486. $fixedTotalTable.find('td[data-key="' + key + '"][data-clone]').each(function () {
  487. $(this).prev().removeClass('isDrag').css({
  488. 'position': 'relative',
  489. 'z-index': 'inherit',
  490. 'left': 'inherit',
  491. 'width': 'inherit',
  492. 'background-color': 'inherit'
  493. });
  494. $(this).remove();
  495. });
  496. }
  497. } else {
  498. $tableBody.find('td[data-key="' + key + '"][data-clone]').each(function () {
  499. $(this).prev().removeClass('isDrag').css({
  500. 'position': 'relative',
  501. 'z-index': 'inherit',
  502. 'left': 'inherit',
  503. 'width': 'inherit',
  504. 'background-color': 'inherit'
  505. });
  506. $(this).remove();
  507. });
  508. if ($totalTable.length > 0) {
  509. $totalTable.find('td[data-key="' + key + '"][data-clone]').each(function () {
  510. $(this).prev().removeClass('isDrag').css({
  511. 'position': 'relative',
  512. 'z-index': 'inherit',
  513. 'left': 'inherit',
  514. 'width': 'inherit',
  515. 'background-color': 'inherit'
  516. });
  517. $(this).remove();
  518. });
  519. }
  520. }
  521. $cloneHead = null;
  522. // 处理 toolbar 事件
  523. if (toolbar) {
  524. if ($dragBar.children('.active').length > 0 && $dragBar.children('.active').attr('data-type') !== $dragBar.attr('data-type')) {
  525. var targetFix = $dragBar.children('.active').attr('data-type'),
  526. i, j, curPos, targetPos;
  527. for (i = 0; i < myTable.cols.length; i++) {
  528. for (j = 0; j < myTable.cols[i].length; j++) {
  529. if (targetFix === 'right' || (targetFix === 'none' && $dragBar.attr('data-type') === 'right')) {
  530. if (typeof targetPos === 'undefined') {
  531. if (myTable.cols[i][j].fixed === 'right') {
  532. targetPos = {x: i, y: j};
  533. } else if (j === myTable.cols[i].length - 1) {
  534. targetPos = {x: i, y: j + 1};
  535. }
  536. }
  537. } else {
  538. if (typeof targetPos === 'undefined' && (!myTable.cols[i][j].fixed || myTable.cols[i][j].fixed === 'right')) {
  539. targetPos = {x: i, y: j};
  540. }
  541. }
  542. if (myTable.cols[i][j].key === curKey) {
  543. curPos = {x: i, y: j};
  544. }
  545. }
  546. }
  547. curColumn['fixed'] = targetFix === 'none' ? false : targetFix;
  548. if (curPos.y !== targetPos.y) {
  549. myTable.cols[curPos.x].splice(curPos.y, 1);
  550. if (curPos.y < targetPos.y) {
  551. targetPos.y -= 1
  552. }
  553. myTable.cols[targetPos.x].splice(targetPos.y, 0, curColumn)
  554. if (myTable.filter && myTable.filter.cache) {
  555. localStorage.setItem(location.pathname + location.hash + myTable.id, _this.deepStringify(myTable.cols))
  556. }
  557. }
  558. table.reload(tableId)
  559. }
  560. $dragBar.removeClass('active')
  561. }
  562. } else {
  563. $that.unbind('click');
  564. }
  565. if ($('#column-remove').is(':visible')) {
  566. $tableHead.find('thead>tr>th[data-key=' + key + ']').addClass(HIDE);
  567. $tableBody.find('tbody>tr>td[data-key="' + key + '"]').addClass(HIDE);
  568. $totalTable.find('tbody>tr>td[data-key="' + key + '"]').addClass(HIDE);
  569. // 同步配置
  570. curColumn['hide'] = true
  571. if (myTable.filter && myTable.filter.cache) {
  572. localStorage.setItem(location.pathname + location.hash + myTable.id, _this.deepStringify(myTable.cols))
  573. }
  574. // 更新下拉隐藏
  575. $('#soul-columns' + tableId).find('li[data-value="' + field + '"]>input').prop('checked', false);
  576. tableFilter.resize(myTable)
  577. }
  578. $('#column-remove').hide();
  579. }
  580. })
  581. });
  582. })
  583. }
  584. },
  585. rowDrag: function (myTable) {
  586. var _this = this,
  587. $table = $(myTable.elem),
  588. $tableBox = $table.next().children('.layui-table-box'),
  589. $fixedBody = $tableBox.children('.layui-table-fixed').children('.layui-table-body').children('table'),
  590. $noFixedBody = $tableBox.children('.layui-table-body').children('table'),
  591. $tableBody = $.merge($tableBox.children('.layui-table-body').children('table'), $fixedBody),
  592. tableId = myTable.id,
  593. isDraging = false,
  594. trigger = myTable.rowDrag.trigger || 'row',
  595. $trs = trigger === 'row' ? $tableBody.children('tbody').children('tr') : $tableBody.find(trigger);
  596. if (trigger !== 'row') {
  597. $tableBody.find(trigger).css('cursor', 'move')
  598. }
  599. $trs.on('mousedown', function (e) {
  600. if (e.button !== 0) {
  601. return;
  602. }
  603. var $this = trigger === 'row' ? $(this) : $(this).parents('tr:eq(0)'),
  604. index = parseInt($this.data('index')),
  605. $bodyTr = $noFixedBody.children('tbody').children('tr[data-index=' + index + ']'),
  606. $cloneTr = $bodyTr.clone().css('visibility', 'hidden'),
  607. $FixBodyTr = $fixedBody.children('tbody').children('tr[data-index=' + index + ']'),
  608. bodyScrollTop = $tableBox.children('.layui-table-body').scrollTop(), // 记录当前滚动条位置
  609. originTop = $this.position().top,
  610. disY = e.clientY - originTop; // 鼠标距离被移动元素上侧的距离
  611. $('body').on('mousemove', function (e) {
  612. if (!isDraging) {
  613. isDraging = true;
  614. // 设置鼠标样式
  615. // $table.next().find('style').append('.layui-table-view .layui-table td{cursor: move;}.layui-table tr{transition: none}')
  616. var style = $table.next().find('style')[0],
  617. sheet = style.sheet || style.styleSheet || {};
  618. _this.addCSSRule(sheet, '.layui-table-view .layui-table td', 'cursor: move')
  619. _this.addCSSRule(sheet, '.layui-table tr', 'transition: none')
  620. $tableBox.addClass('noselect'); // 禁止选中文本
  621. $bodyTr.after($cloneTr);
  622. $bodyTr.css({
  623. 'position': 'absolute',
  624. 'z-index': 1
  625. })
  626. $FixBodyTr.each(function () {
  627. $(this).after($(this).clone().css('visibility', 'hidden'))
  628. $(this).css({
  629. 'position': 'absolute',
  630. 'z-index': 102
  631. })
  632. })
  633. }
  634. var top = e.clientY - disY + ($tableBox.children('.layui-table-body').scrollTop() - bodyScrollTop), // 计算当前被移动行top位置应该哪里
  635. trTop = $cloneTr.position().top, //当前行所在位置
  636. $UpTr = $bodyTr.prev(),
  637. hasUpTr = $UpTr.length > 0,
  638. $downTr = $cloneTr.next(),
  639. hasDownTr = $downTr.length > 0,
  640. upMove = hasUpTr && (trTop - top > $UpTr.height() / 2.0),
  641. downMove = hasDownTr && (top - trTop > $downTr.height() / 2.0);
  642. if (trTop - top > 0 ? !hasUpTr : !hasDownTr) {
  643. $bodyTr.css('top', trTop);
  644. $FixBodyTr.each(function () {
  645. $(this).css('top', trTop);
  646. })
  647. return;
  648. }
  649. $bodyTr.css('top', top);
  650. $FixBodyTr.each(function () {
  651. $(this).css('top', top);
  652. })
  653. if (upMove) {
  654. updateDataIndex($bodyTr, -1)
  655. $cloneTr.after(updateDataIndex($UpTr, 1));
  656. $FixBodyTr.each(function () {
  657. updateDataIndex($(this), -1)
  658. $(this).next().after(updateDataIndex($(this).prev(), 1));
  659. })
  660. } else if (downMove) {
  661. updateDataIndex($bodyTr, 1).before(updateDataIndex($downTr, -1))
  662. $FixBodyTr.each(function () {
  663. updateDataIndex($(this), 1);
  664. $(this).before(updateDataIndex($(this).next().next(), -1));
  665. })
  666. }
  667. // 同步 data-index
  668. function updateDataIndex($el, diff) {
  669. var tempIndex = parseInt($el.data('index')) + diff;
  670. $el.data('index', tempIndex);
  671. $el.attr('data-index', tempIndex);
  672. return $el
  673. }
  674. }).on('mouseup', function (e) {
  675. $('body').off('mousemove').off('mouseup');
  676. if (isDraging) {
  677. isDraging = false;
  678. $tableBox.removeClass('noselect'); // 取消禁止选中文本
  679. $bodyTr.css({'position': 'inherit', 'z-index': 'inherit'});
  680. $bodyTr.next().remove();
  681. $FixBodyTr.each(function () {
  682. $(this).css({'position': 'inherit', 'z-index': 'inherit'});
  683. $(this).next().remove()
  684. })
  685. // 恢复样式
  686. var style = $table.next().find('style')[0],
  687. sheet = style.sheet || style.styleSheet || {},
  688. rules = sheet.cssRules || sheet.rules;
  689. layui.each(rules, function (i, item) {
  690. if (item.selectorText === ('.layui-table-view .layui-table td')) {
  691. item.style.cursor = 'default';
  692. }
  693. });
  694. var newIndex = $this.index();
  695. if (newIndex !== index) { // 有位置变动
  696. if (typeof myTable.rowDrag.done === 'function') {
  697. var cache = layui.table.cache[tableId],
  698. row = cache.splice(index, 1)[0];
  699. cache.splice(newIndex, 0, row);
  700. myTable.rowDrag.done.call(myTable, {
  701. row: row,
  702. newIndex: newIndex,
  703. oldIndex: index,
  704. cache: cache
  705. })
  706. }
  707. }
  708. }
  709. })
  710. })
  711. },
  712. fixTableRemember: function (myTable, dict) {
  713. if (myTable.filter && myTable.filter.cache) {
  714. if (dict && dict.rule) {
  715. myTable.cols[dict.rule.selectorText.split('-')[3]][dict.rule.selectorText.split('-')[4]].width = dict.rule.style.width.replace('px', '');
  716. }
  717. localStorage.setItem(location.pathname + location.hash + myTable.id, this.deepStringify(myTable.cols))
  718. }
  719. },
  720. overflow: function (myTable) {
  721. var options = {};
  722. if (typeof myTable.overflow === 'string') {
  723. options = {
  724. type: myTable.overflow
  725. }
  726. } else if (typeof myTable.overflow === 'object') {
  727. options = myTable.overflow
  728. } else {
  729. return;
  730. }
  731. var $table = $(myTable.elem),
  732. layBody = $table.next().find('.layui-table-body'),
  733. tooltipIndex,
  734. hoverTime = options.hoverTime || 0,
  735. tooltipTimeOut,
  736. color = options.color || 'white',
  737. bgColor = options.bgColor || 'black',
  738. minWidth = options.minWidth || 300,
  739. maxWidth = options.maxWidth || 300;
  740. if (options.type === 'tips') {
  741. layBody.off('mouseenter', 'td').on('mouseenter', 'td', function () {
  742. var _this = this;
  743. tooltipTimeOut = setTimeout(function () {
  744. toopTip.call(_this)
  745. }, hoverTime)
  746. }).on('mouseleave', 'td', function () {
  747. toopTip.call(this, 'hide')
  748. })
  749. function toopTip(hide) {
  750. clearTimeout(tooltipTimeOut);
  751. var othis = $(this)
  752. , elemCell = othis.children('.layui-table-cell')
  753. , width = elemCell.outerWidth()
  754. , layerWidth = width < minWidth ? minWidth : width > maxWidth ? maxWidth : width;
  755. if (othis.data('off')) return;
  756. if (hide) {
  757. layer.close(tooltipIndex)
  758. } else if (elemCell.prop('scrollWidth') > width) {
  759. tooltipIndex = layer.tips('<span style="color: ' + color + '">' + $(this).text() + '</span>', this, {
  760. tips: [1, bgColor],
  761. maxWidth: layerWidth,
  762. time: 0
  763. });
  764. }
  765. }
  766. } else if (options.type === 'title') {
  767. layBody.off('mouseenter', 'td').on('mouseenter', 'td', function () {
  768. var othis = $(this)
  769. , elemCell = othis.children('.layui-table-cell');
  770. if (othis.data('off')) return;
  771. if (elemCell.prop('scrollWidth') > elemCell.outerWidth()) {
  772. elemCell.attr('title', $(this).text())
  773. }
  774. })
  775. }
  776. },
  777. // 右键菜单配置
  778. contextmenu: function (myTable) {
  779. var $table = $(myTable.elem),
  780. $tableBox = $table.next().children('.layui-table-box'),
  781. $tableHead = $.merge($tableBox.children('.layui-table-header').children('table'), $tableBox.children('.layui-table-fixed').children('.layui-table-header').children('table')),
  782. $fixedBody = $tableBox.children('.layui-table-fixed').children('.layui-table-body').children('table'),
  783. $tableBody = $.merge($tableBox.children('.layui-table-body').children('table'), $fixedBody),
  784. $totalTable = $table.next().children('.layui-table-total').children('table'),
  785. tableId = myTable.id,
  786. header = myTable.contextmenu ? myTable.contextmenu.header : '',
  787. body = myTable.contextmenu ? myTable.contextmenu.body : '',
  788. total = myTable.contextmenu ? myTable.contextmenu.total : '',
  789. options = {
  790. header: {box: $tableHead, tag: 'th', opts: header, cols: {}},
  791. body: {box: $tableBody, tag: 'td', opts: body, cols: {}, isBody: true},
  792. total: {box: $totalTable, tag: 'td', opts: total, cols: {}}
  793. },
  794. hasColsContext = false;
  795. for (var i = 0; i < myTable.cols.length; i++) {
  796. for (var j = 0; j < myTable.cols[i].length; j++) {
  797. if (myTable.cols[i][j].contextmenu) {
  798. hasColsContext = true
  799. options.header.cols[myTable.cols[i][j].key] = myTable.cols[i][j].contextmenu.header
  800. options.body.cols[myTable.cols[i][j].key] = myTable.cols[i][j].contextmenu.body
  801. options.total.cols[myTable.cols[i][j].key] = myTable.cols[i][j].contextmenu.total
  802. }
  803. }
  804. }
  805. if (!myTable.contextmenu && !hasColsContext) {
  806. return;
  807. }
  808. for (var name in options) {
  809. (function (name) {
  810. options[name].box.find(options[name].tag).on('contextmenu', function (e) {
  811. $('#soul-table-contextmenu-wrapper').remove();
  812. $('body').append('<div id="soul-table-contextmenu-wrapper"></div>');
  813. $('#soul-table-contextmenu-wrapper').on('click', function (e) {
  814. e.stopPropagation()
  815. })
  816. var curColsOpts = options[name].cols[$(this).data('key').substr($(this).data('key').indexOf('-') + 1)];
  817. if (curColsOpts === false) {
  818. return false
  819. } else if (curColsOpts && curColsOpts.length > 0) {
  820. genePanel($('#soul-table-contextmenu-wrapper'), e.clientX, e.clientY, curColsOpts, $(this), options[name].box, options[name].tag, options[name].isBody);
  821. return false
  822. } else if (options[name].opts === false) {
  823. return false
  824. } else if (options[name].opts && options[name].opts.length > 0) {
  825. genePanel($('#soul-table-contextmenu-wrapper'), e.clientX, e.clientY, options[name].opts, $(this), options[name].box, options[name].tag, options[name].isBody);
  826. return false
  827. }
  828. })
  829. })(name)
  830. }
  831. $('body').on('click', function () {
  832. $('#soul-table-contextmenu-wrapper').remove();
  833. })
  834. function genePanel($parent, left, top, options, $this, box, tag, isBody) {
  835. var html = [], i;
  836. html.push('<ul class="soul-table-contextmenu">');
  837. for (i = 0; i < options.length; i++) {
  838. html.push('<li data-index="' + i + '" class="' + (options[i].children && options[i].children.length > 0 ? 'contextmenu-children' : '') + '">')
  839. if (options[i].icon) {
  840. html.push('<i class="prefixIcon ' + options[i].icon + '" />')
  841. } else {
  842. html.push('<i class="prefixIcon" />')
  843. }
  844. html.push(options[i].name)
  845. if (options[i].children && options[i].children.length > 0) {
  846. html.push('<i class="endIcon layui-icon layui-icon-right" />')
  847. }
  848. html.push('</li>')
  849. }
  850. html.push('</ul>');
  851. $parent.append(html.join(''));
  852. var $curPanel = $parent.children().last();
  853. if (top + $curPanel.outerHeight() > $('body').prop('scrollHeight')) {
  854. top = top - $curPanel.outerHeight()
  855. if (top < 0) {
  856. top = 0
  857. }
  858. }
  859. if ($parent.parent().data('direction') === 'left' && ($parent.offset().left - $curPanel.outerWidth()) > 0) {
  860. left = -$curPanel.outerWidth();
  861. $curPanel.data('direction', 'left')
  862. } else if (left + $curPanel.outerWidth() + $parent.offset().left > $('body').prop('scrollWidth')) {
  863. left = left - $curPanel.outerWidth() - $parent.outerWidth()
  864. if (left + $parent.offset().left < 0) {
  865. left = -$parent.offset().left
  866. }
  867. $curPanel.data('direction', 'left')
  868. }
  869. $curPanel.css({
  870. top: top + 'px',
  871. left: left + 'px'
  872. })
  873. for (i = 0; i < options.length; i++) {
  874. if (typeof options[i].click === "function") {
  875. (function (i) {
  876. $parent.children('.soul-table-contextmenu:last').children('li[data-index="' + i + '"]').on('click', function () {
  877. var index = $this.parents('tr:eq(0)').data('index'),
  878. tr = box.find('tr[data-index="' + index + '"]'),
  879. row = layui.table.cache[tableId][index];
  880. options[i].click.call(myTable, {
  881. cell: $this,
  882. 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') + '"]'),
  883. trElem: box.children('tbody').children('tr[data-index="' + index + '"]'),
  884. text: $this.text(),
  885. field: $this.data('field'),
  886. del: !isBody ? '' : function () {
  887. table.cache[tableId][index] = [];
  888. tr.remove();
  889. table.resize(tableId);
  890. },
  891. update: !isBody ? '' : function (fields) {
  892. fields = fields || {};
  893. layui.each(fields, function (key, value) {
  894. if (key in row) {
  895. var templet, td = tr.children('td[data-field="' + key + '"]');
  896. row[key] = value;
  897. table.eachCols(tableId, function (i, item2) {
  898. if (item2.field == key && item2.templet) {
  899. templet = item2.templet;
  900. }
  901. });
  902. td.children('.layui-table-cell').html(function () {
  903. return templet ? function () {
  904. return typeof templet === 'function'
  905. ? templet(row)
  906. : layui.laytpl($(templet).html() || value).render(row)
  907. }() : value;
  908. }());
  909. td.data('content', value);
  910. }
  911. });
  912. },
  913. row: isBody ? row : {},
  914. })
  915. $('#soul-table-contextmenu-wrapper').remove();
  916. })
  917. })(i)
  918. }
  919. }
  920. $parent.children('.soul-table-contextmenu:last').children('li').on('mouseenter', function (e) {
  921. e.stopPropagation()
  922. $(this).siblings('.contextmenu-children').children('ul').remove();
  923. if ($(this).hasClass('contextmenu-children')) {
  924. genePanel($(this), $(this).outerWidth(), $(this).position().top, options[$(this).data('index')].children, $this, box, tag, isBody)
  925. }
  926. })
  927. }
  928. },
  929. fixTotal: function (myTable) {
  930. var $table = $(myTable.elem),
  931. $total = $table.next().children('.layui-table-total'),
  932. style = $table.next().find('style')[0],
  933. sheet = style.sheet || style.styleSheet || {};
  934. if ($total.length > 0) {
  935. var $tableBox = $table.next().children('.layui-table-box'),
  936. $fixedLeft = $tableBox.children('.layui-table-fixed-l').children('.layui-table-body').children('table').children('tbody').children('tr:eq(0)').children('td'),
  937. $fixedRight = $tableBox.children('.layui-table-fixed-r').children('.layui-table-body').children('table').children('tbody').children('tr:eq(0)').children('td'),
  938. html = [];
  939. $total.children('.layui-table-total-fixed').remove()
  940. if ($fixedLeft.length > 0) {
  941. this.addCSSRule(sheet, '.layui-table-total-fixed-l .layui-table-patch', 'display: none')
  942. $table.next().css('position', 'relative');
  943. 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>');
  944. $fixedLeft.each(function () {
  945. if ($(this).data('key')) {
  946. html.push($total.children('table:eq(0)').find('[data-key="' + $(this).data('key') + '"]').prop("outerHTML"))
  947. }
  948. })
  949. html.push('</tr></tbody></table>');
  950. $total.append(html.join(''))
  951. }
  952. if ($fixedRight.length > 0) {
  953. this.addCSSRule(sheet, '.layui-table-total-fixed-r td:first-child', 'border-left:1px solid #e6e6e6')
  954. this.addCSSRule(sheet, '.layui-table-total-fixed-r td:last-child', 'border-left: none')
  955. $table.next().css('position', 'relative');
  956. html = [];
  957. 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>');
  958. $fixedRight.each(function () {
  959. html.push($total.children('table:eq(0)').find('[data-key="' + $(this).data('key') + '"]').prop("outerHTML"))
  960. })
  961. html.push('</tr></tbody></table>')
  962. $total.append(html.join(''))
  963. }
  964. }
  965. },
  966. fixResizeRightFixed: function (myTable) {
  967. var _this = this,
  968. $table = $(myTable.elem),
  969. $tableBox = $table.next().children('.layui-table-box'),
  970. $fixedHead = $tableBox.children('.layui-table-fixed-r').children('.layui-table-header').children('table'),
  971. dict = {}, _BODY = $('body'), _DOC = $(document), resizing, ELEM_SORT = 'layui-table-sort',
  972. ELEM_NO_SORT = 'layui-table-sort-invalid';
  973. if ($fixedHead.length > 0) {
  974. $fixedHead.find('th').off('mousemove').on('mousemove', function (e) {
  975. var othis = $(this)
  976. , oLeft = othis.offset().left
  977. , pLeft = e.clientX - oLeft;
  978. if (othis.data('unresize') || dict.resizeStart) {
  979. return;
  980. }
  981. if (othis.width() - pLeft <= 10) {
  982. _BODY.css('cursor', 'initial')
  983. }
  984. dict.allowResize = pLeft <= 10; //是否处于拖拽允许区域
  985. _BODY.css('cursor', (dict.allowResize ? 'col-resize' : ''));
  986. }).off('mousedown').on('mousedown', function (e) {
  987. var othis = $(this);
  988. if (dict.allowResize) {
  989. othis.find('.' + ELEM_SORT).removeClass(ELEM_SORT).addClass(ELEM_NO_SORT)
  990. var key = othis.data('key');
  991. e.preventDefault();
  992. dict.resizeStart = true; //开始拖拽
  993. dict.offset = [e.clientX, e.clientY]; //记录初始坐标
  994. _this.getCssRule(myTable, key, function (item) {
  995. var width = item.style.width || othis.outerWidth();
  996. dict.rule = item;
  997. dict.ruleWidth = parseFloat(width);
  998. dict.othis = othis;
  999. dict.minWidth = othis.data('minwidth') || myTable.cellMinWidth;
  1000. });
  1001. }
  1002. });
  1003. //拖拽中
  1004. _DOC.on('mousemove', function (e) {
  1005. if (dict.resizeStart) {
  1006. layui.soulTable.fixTableRemember(myTable, dict)
  1007. e.preventDefault();
  1008. if (dict.rule) {
  1009. var setWidth = dict.ruleWidth - e.clientX + dict.offset[0];
  1010. if (setWidth < dict.minWidth) setWidth = dict.minWidth;
  1011. dict.rule.style.width = setWidth + 'px';
  1012. }
  1013. resizing = 1
  1014. }
  1015. }).on('mouseup', function (e) {
  1016. if (dict.resizeStart) {
  1017. setTimeout(function () {
  1018. dict.othis.find('.' + ELEM_NO_SORT).removeClass(ELEM_NO_SORT).addClass(ELEM_SORT)
  1019. _BODY.css('cursor', '');
  1020. dict = {};
  1021. _this.scrollPatch(myTable);
  1022. }, 30)
  1023. }
  1024. if (resizing === 2) {
  1025. resizing = null;
  1026. }
  1027. });
  1028. }
  1029. },
  1030. fixFixedScroll: function (myTable) {
  1031. var $table = $(myTable.elem),
  1032. layFixed = $table.next().children('.layui-table-box').children('.layui-table-fixed'),
  1033. layMain = $table.next().children('.layui-table-box').children('.layui-table-main');
  1034. layFixed.on('mouseenter', function () {
  1035. $(this).children('.layui-table-body').addClass('soul-fixed-scroll').on('scroll', function () {
  1036. var scrollTop = $(this).scrollTop()
  1037. // layFixed.children('.layui-table-body[class!="soul-fixed-scroll"]').scrollTop(scrollTop);
  1038. layMain.scrollTop(scrollTop);
  1039. })
  1040. }).on('mouseleave', function () {
  1041. $(this).children('.layui-table-body').removeClass('soul-fixed-scroll').off('scroll');
  1042. })
  1043. },
  1044. scrollPatch: function (myTable) {
  1045. var $table = $(myTable.elem),
  1046. layHeader = $table.next().children('.layui-table-box').children('.layui-table-header'),
  1047. layTotal = $table.next().children('.layui-table-total'),
  1048. layMain = $table.next().children('.layui-table-box').children('.layui-table-main'),
  1049. layFixed = $table.next().children('.layui-table-box').children('.layui-table-fixed'),
  1050. layFixRight = $table.next().children('.layui-table-box').children('.layui-table-fixed-r'),
  1051. layMainTable = layMain.children('table'),
  1052. scollWidth = layMain.width() - layMain.prop('clientWidth'),
  1053. scollHeight = layMain.height() - layMain.prop('clientHeight'),
  1054. outWidth = layMainTable.outerWidth() - layMain.width() //表格内容器的超出宽度
  1055. //添加补丁
  1056. , addPatch = function (elem) {
  1057. if (scollWidth && scollHeight) {
  1058. elem = elem.eq(0);
  1059. if (!elem.find('.layui-table-patch')[0]) {
  1060. var patchElem = $('<th class="layui-table-patch"><div class="layui-table-cell"></div></th>'); //补丁元素
  1061. patchElem.find('div').css({
  1062. width: scollWidth
  1063. });
  1064. elem.find('tr').append(patchElem);
  1065. }
  1066. } else {
  1067. elem.find('.layui-table-patch').remove();
  1068. }
  1069. }
  1070. addPatch(layHeader);
  1071. addPatch(layTotal);
  1072. //固定列区域高度
  1073. var mainHeight = layMain.height()
  1074. , fixHeight = mainHeight - scollHeight;
  1075. layFixed.find('.layui-table-body').css('height', layMainTable.height() >= fixHeight ? fixHeight : 'auto');
  1076. //表格宽度小于容器宽度时,隐藏固定列
  1077. layFixRight[outWidth > 0 ? 'removeClass' : 'addClass'](HIDE);
  1078. //操作栏
  1079. layFixRight.css('right', scollWidth - 1);
  1080. },
  1081. /**
  1082. * 一键粘贴
  1083. * @param {String} text [需要 copy 的属性,默认是 innerText,主要用途例如赋值 a 标签上的 href 链接]
  1084. *
  1085. * range + selection
  1086. *
  1087. * 1.创建一个 range
  1088. * 2.把内容放入 range
  1089. * 3.把 range 放入 selection
  1090. *
  1091. * 注意:参数 attr 不能是自定义属性
  1092. * 注意:对于 user-select: none 的元素无效
  1093. * 注意:当 id 为 false 且 attr 不会空,会直接复制 attr 的内容
  1094. */
  1095. copy: function (text) {
  1096. var target;
  1097. if (text) {
  1098. target = document.createElement('div');
  1099. target.id = 'tempTarget';
  1100. target.style.opacity = '0';
  1101. target.innerText = text;
  1102. document.body.appendChild(target);
  1103. } else {
  1104. target = document.querySelector('#' + id);
  1105. }
  1106. try {
  1107. var range = document.createRange();
  1108. range.selectNode(target);
  1109. window.getSelection().removeAllRanges();
  1110. window.getSelection().addRange(range);
  1111. document.execCommand('copy');
  1112. window.getSelection().removeAllRanges();
  1113. } catch (e) {
  1114. console.log('复制失败')
  1115. }
  1116. if (text) {
  1117. // remove temp target
  1118. target.parentElement.removeChild(target);
  1119. }
  1120. },
  1121. addCSSRule: function (sheet, selector, rules, index) {
  1122. if ('insertRule' in sheet) {
  1123. sheet.insertRule(selector + '{' + rules + '}', index)
  1124. } else if ('addRule' in sheet) {
  1125. sheet.addRule(selector, rules, index)
  1126. }
  1127. },
  1128. deepStringify: function (obj) {
  1129. var JSON_SERIALIZE_FIX = {
  1130. PREFIX: "[[JSON_FUN_PREFIX_",
  1131. SUFFIX: "_JSON_FUN_SUFFIX]]"
  1132. };
  1133. return JSON.stringify(obj, function (key, value) {
  1134. if (typeof value === 'function') {
  1135. return JSON_SERIALIZE_FIX.PREFIX + value.toString() + JSON_SERIALIZE_FIX.SUFFIX;
  1136. }
  1137. return value;
  1138. });
  1139. },
  1140. deepParse: function (str) {
  1141. var JSON_SERIALIZE_FIX = {
  1142. PREFIX: "[[JSON_FUN_PREFIX_",
  1143. SUFFIX: "_JSON_FUN_SUFFIX]]"
  1144. };
  1145. return JSON.parse(str, function (key, value) {
  1146. if (typeof value === 'string' &&
  1147. value.indexOf(JSON_SERIALIZE_FIX.SUFFIX) > 0 && value.indexOf(JSON_SERIALIZE_FIX.PREFIX) === 0) {
  1148. return eval("(" + value.replace(JSON_SERIALIZE_FIX.PREFIX, "").replace(JSON_SERIALIZE_FIX.SUFFIX, "") + ")");
  1149. }
  1150. return value;
  1151. }) || {};
  1152. },
  1153. clearFilter: function (myTable) {
  1154. tableFilter.clearFilter(myTable);
  1155. },
  1156. cache: tableFilter.cache
  1157. }
  1158. // 输出
  1159. exports('soulTable', mod);
  1160. });