const _token = ''; let insTb; let Tools = { getInsTb: function () { return insTb; }, setInsTb: function (ins) { insTb = ins; } } layui.use(['jquery', 'form', 'layer', 'miniTab', 'laytpl', 'table'], function () { let $ = layui.jquery, form = layui.form, layer = layui.layer, miniTab = layui.miniTab, table = layui.table; let modifyUrl = $('#row-modify').data('url'); miniTab.listen(); //页面加载时,根据需要加载富文本编辑器 if ($('.editor').length) { editor(); } //监听配置页面提交 form.on('submit(saveConfig)', function (data) { let url = $(data.elem).data('url'); $.post(url, data.field, function (res) { layer.msg(res.msg); if (res.code === 0) { setTimeout(function () { //关闭当前弹出层 miniTab.deleteCurrentByIframe(); }, 1000) } }); return false; }); //监听提交 form.on('submit(saveBtn)', function (data) { let url = $(data.elem).data('url'); let isTab = $(data.elem).data('tab'); let index = layer.load(2); $.post(url, data.field, function (res) { layer.close(index); layer.msg(res.msg); if (res.code === 0) { if (isTab) { //关闭tab setTimeout(function () { miniTab.deleteCurrentByIframe(); }, 1000) } else { //刷新父级列表 parent.layui.$('[data-table-refresh]').trigger("click"); setTimeout(function () { //关闭当前弹出层 let iframeIndex = parent.layer.getFrameIndex(window.name); parent.layer.close(iframeIndex); }, 1000) } } }); return false; }); //监听关闭 form.on('submit(close)', function () { let iframeIndex = parent.layer.getFrameIndex(window.name); parent.layer.close(iframeIndex); return false; }); //监听单元格编辑 table.on('edit(table-container)', function (obj) { let insTb = Tools.getInsTb(); $.post(modifyUrl, {id: obj.data.id, field: obj.field, value: obj.value}, function (res) { layer.msg(res.msg) if (res.code !== 0 || obj.field === 'sort') { refreshTab(insTb); } }) }); //监听状态改变 form.on('switch(changeStatus)', function (obj) { let val = obj.elem.checked ? 1 : 0; let insTb = Tools.getInsTb(); $.post(modifyUrl, {id: this.value, field: this.name, value: val}, function (res) { layer.msg(res.msg) if (res.code !== 0) { setTimeout(function () { refreshTab(insTb); }, 1000) } }) }); // 监听搜索操作 form.on('submit(data-search-btn)', function (data) { //执行搜索重载 table.reload('table-container', { page: {curr: 1} , where: {searchParams: data.field} }, 'data'); return false; }); //监听工具条 注意区别toolbar和tool toolbar是表头上的工具条 tool是行中的工具条 table.on('toolbar(table-container)', function (obj) { let layEvent = obj.event; let insTb = Tools.getInsTb(); let url = $($(this).context).data('href') let title = $($(this).context).data('title') let width = $($(this).context).data('width') ? $($(this).context).data('width') : '100%'; let height = $($(this).context).data('height') ? $($(this).context).data('height') : '100%'; // debugger; switch (layEvent) { // toolbar 删除 case 'del': let checkStatus = table.checkStatus('table-container'); if (checkStatus.data.length <= 0) { layer.msg('请先选择数据'); return false; } let selected = checkStatus.data; let ids = []; $.each(selected, function (index, val) { ids.push(val.id); }) delRow(url, ids, insTb); return false; // toolbar 刷新 case 'refresh': refreshTab(insTb); return false; // toolbar 搜索 case 'search': let search = $('.table-search-fieldset'); if (search.hasClass('div-show')) { search.css('display', 'none').removeClass('div-show'); } else { search.css('display', 'block').addClass('div-show'); } return false; // 其他 默认为打开弹出层 default: if (layEvent !== 'LAYTABLE_COLS' && layEvent !== 'LAYTABLE_EXPORT') { openLayer(url, title, width, height); return false; } } }); //监听行工具条 table.on('tool(table-container)', function (obj) { let data = obj.data; let layEvent = obj.event; let url = $($(this).context).data('href'); let title = $($(this).context).data('title'); let width = $($(this).context).data('width') ? $($(this).context).data('width') : '100%'; let height = $($(this).context).data('height') ? $($(this).context).data('height') : '100%'; let insTb = Tools.getInsTb(); switch (layEvent) { // 行 删除 case 'del': let ids = [data.id]; delRow(url, ids, insTb); return false; //其他 默认为打开弹出层 default: openLayer(url, title, width, height); return false; } }); /** 图片预览 **/ $('body').on('click', '.layui-layer-photos', function () { layer.photos({ photos: '.layui-layer-photos' // 指向图片的父容器 ,anim: 5 //0-6的选择,指定弹出图片动画类型,默认随机(3.0之前的版本用shift参数) }); }) }); //富文本编辑器,单页面可以添加多个,需要使用不同的ID TODO 使用的原CMS操作 function editor() { layui.use(['jquery', 'wangEditor'], function () { let $ = layui.jquery, E = layui.wangEditor; if ($('.editor').length) { $.each($('.editor'), function (i) { var wang = new E(this); var $text1 = $(this).parent().find('textarea'); wang.customConfig.onchange = function (html) { // 监控变化,同步更新到 textarea $text1.val(html) } wang.customConfig.pasteTextHandle = function (content) { if (content == '' && !content) return '';//其中content就是你zhantie过来的原始的文本 return removeFormatWrd(content); }; function removeFormatWrd(html) { // console.log(html) // html = html.replace(/<xml>[\s\S]*?<\/xml>/ig, ''); // html = html.replace(/<style>[\s\S]*?<\/style>/ig, ''); // html = html.replace(/<\/?[^>]*>/g, ''); // html = html.replace(/[ | ]*\n/g, '\n'); // html = html.replace(/ /ig, ''); //上面代码是不要任何样式,纯文本 //下面代码,保留从相关文档中的粘贴过来时的样式 html = html.replace(/<\/?SPANYES[^>]*>/gi, "");// Remove all SPAN tags html = html.replace(/<(\w[^>]*) class=([^|>]*)([^>]*)/gi, "<$1$3"); // Remove Class attributes html = html.replace(/<(\w[^>]*) style="([^"]*)"([^>]*)/gi, "<$1$3"); // Remove Style attributes html = html.replace(/<(\w[^>]*) lang=([^|>]*)([^>]*)/gi, "<$1$3");// Remove Lang attributes html = html.replace(/<?xml[^>]*>/gi, "");// Remove XML elements and declarations html = html.replace(/<\/?\w+:[^>]*>/gi, "");// Remove Tags with XML namespace declarations: <o:p></o:p> html = html.replace(/ /, "");// Replace the html = html.replace(/<xml>[\s\S]*?<\/xml>/ig, ''); html = html.replace(/<html>[\s\S]*?<\/html>/ig, ''); html = html.replace(/<head>[\s\S]*?<\/head>/ig, ''); html = html.replace(/<style>[\s\S]*?<\/style>/ig, ''); html = html.replace(/<html<body/ig, '<html><body'); html = html.replace(/<\/html<body>/ig, '</body></html>'); html = html.replace(/\n(\n)*( )*(\n)*\n/gi, '\n'); return html; } wang.customConfig.menus = [ 'head', // 标题 'bold', // 粗体 'fontSize', // 字号 'fontName', // 字体 'italic', // 斜体 'underline', // 下划线 'strikeThrough', // 删除线 'foreColor', // 文字颜色 'backColor', // 背景颜色 'link', // 插入链接 'list', // 列表 'justify', // 对齐方式 'quote', // 引用 'emoticon', // 表情 'image', // 插入图片 'table', // 表格 'video', // 插入视频 'code', // 插入代码 'undo', // 撤销 'redo', // 重复 ] // 隐藏“网络图片”tab wang.customConfig.showLinkImg = true wang.customConfig.uploadFileName = 'wang_img[]' wang.customConfig.showLinkVideo = true wang.customConfig.uploadImgHooks = { before: function (xhr, editor, files) { // 图片上传之前触发 // xhr 是 XMLHttpRequst 对象,editor 是编辑器对象,files 是选择的图片文件 // 如果返回的结果是 {prevent: true, msg: 'xxxx'} 则表示用户放弃上传 }, success: function (xhr, editor, result) { // 图片上传并返回结果,图片插入成功之后触发 // xhr 是 XMLHttpRequst 对象,editor 是编辑器对象,result 是服务器端返回的结果 }, fail: function (xhr, editor, result) { // 图片上传并返回结果,但图片插入错误时触发 // xhr 是 XMLHttpRequst 对象,editor 是编辑器对象,result 是服务器端返回的结果 }, error: function (xhr, editor) { // 图片上传出错时触发 // xhr 是 XMLHttpRequst 对象,editor 是编辑器对象 }, timeout: function (xhr, editor) { // 图片上传超时时触发 // xhr 是 XMLHttpRequst 对象,editor 是编辑器对象 }, // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式,可使用该配置 // (但是,服务器端返回的必须是一个 JSON 格式字符串!!!否则会报错) customInsert: function (insertImg, result, editor) { // 图片上传并返回结果,自定义插入图片的事件(而不是编辑器自动插入图片!!!) // insertImg 是插入图片的函数,editor 是编辑器对象,result 是服务器端返回的结果 // console.log(result); if (result.errno == 0) { if (result.data.length > 0) { $.each(result.data, function (i, val) { insertImg(val); }) } } else { // 错误提示 layer.msg(result.data[0]) } } } wang.customConfig.uploadImgParams = {_token: _token} wang.customConfig.uploadVideoParams = {_token: _token} //上传视频 wang.customConfig.uploadVideoServer = "/manager/upload/video.html" wang.customConfig.uploadVideoHooks = { customInsert: function (insertImg, result, editor) { var url = result.data.src;//获取后台返回的url insertImg(url); } }; wang.customConfig.uploadImgServer = '/manager/upload/wangImage.html' wang.customConfig.customAlert = function (info) { // info 是需要提示的内容 layer.msg(info) } wang.create(); wang.txt.html($text1.val()) $text1.val(wang.txt.html()) editorSelector = '.editor'; $(editorSelector + " .w-e-toolbar").eq(i).append('<div class="w-e-menu"><a class="_wangEditor_btn_fullscreen" onclick="window.wangEditor.fullscreen.toggleFullscreen(this)">全屏</a></div>'); window.wangEditor.fullscreen = { // editor create之后调用 toggleFullscreen: function (editorSelector) { $(editorSelector).closest('.editor-text').toggleClass('fullscreen-editor') if ($(editorSelector).text() == '全屏') { $(editorSelector).text('退出全屏'); } else { $(editorSelector).text('全屏'); } }, charu: function (obj) { insertHtmlAtCaret('<img src="' + $(obj).attr('src') + '">', $(obj).closest('.editor').find('.w-e-text')) $(obj).closest('.editor').find('.w-e-panel-container').remove(); } }; $(editorSelector + " .w-e-toolbar").eq(i).append('<div class="w-e-menu"><a class="_wangEditor_btn_viewsource' + i + '" data-id="' + i + '" onclick="window.wangEditor.viewsource.toggleViewsource(this)">源码</a></div>'); window.wangEditor.viewsource = { toggleViewsource: function (editorSelector) { $('.editor').each(function (i) { if ($(editorSelector).attr('data-id') == i) { if ($(editorSelector).text() == '源码') { $(editorSelector).text('返回'); $(this).addClass('active') $(this).parent().find('textarea.layui-textarea').removeClass('layui-hide') } else { $(editorSelector).text('源码'); $(this).removeClass('active') $(this).parent().find('textarea.layui-textarea').addClass('layui-hide') } } }) }, recovery: function (editorSelector) { $('.editor').each(function (i) { if ($(editorSelector).text() == '返回') { editorHtml = $(editorSelector).closest('.editor').find('.w-e-text').html().replace(/</ig, "<").replace(/>/ig, ">").replace(/ /ig, " "); $(editorSelector).text('源码'); $(editorSelector).closest('.editor').find('.w-e-text').html(editorHtml); $(editorSelector).closest('.editor').parent().find('textarea').val(editorHtml) } }) } }; $(editorSelector + " .w-e-toolbar").eq(i).append('<div class="w-e-menu"><a class="_wangEditor_btn_eliminate' + i + '" data-id="' + i + '" onclick="window.wangEditor.eliminate.toggleViewsource(this)">清除格式</a></div>'); window.wangEditor.eliminate = { toggleViewsource: function (editorSelector) { $('.editor').each(function (i) { if ($(editorSelector).attr('data-id') == i) { var str = $(editorSelector).closest('.editor').find('.w-e-text').html(); str = str.replace(/<xml>[\s\S]*?<\/xml>/ig, ''); str = str.replace(/<style>[\s\S]*?<\/style>/ig, ''); str = str.replace(/<\/?[^>]*>/g, ''); str = str.replace(/[ | ]*\n/g, '\n'); str = str.replace(/ /ig, ''); $(editorSelector).closest('.editor').find('.w-e-text').html(str); } }) } }; var that = $(this) that.removeClass('active'); that.parent().find('textarea').addClass('layui-hide') that.parent().find('textarea').on('input propertychange', function () { that.find('.w-e-text').html($(this).val()) }) }); } }) getblur(); } let fwqpage = 2; function getImgList(id) { layui.use(['jquery'], function () { let $ = layui.jquery var html = ''; var pageBtn = ''; fwqpage = 1; $.ajax('/manager/file/list', { data: { type: 'img', page: fwqpage, size: 20 }, headers: { 'X-CSRF-TOKEN': _token }, dataType: 'json',//服务器返回json格式数据 type: 'post',//HTTP请求类型 timeout: 10000,//超时时间设置为10秒; success: function (data) { if (data.code == 0) { if (data.data.length > 0) { $.each(data.data, function (i, item) { html += '<span><img src="' + item.src + '" onclick="window.wangEditor.fullscreen.charu(this)"></span>' }) $('#' + id).closest('.editor').find('.w-e-serverImgs .top-box').append(html) if (data.data.length >= 20) { pageBtn = '<a href="javascript:;" data-id="' + id + '" onclick="getImgMore(this)">加载更多</a>'; $('#' + id).closest('.editor').find('.w-e-serverImgs .lower-box').append(pageBtn) } } else { layer.msg(data.msg) } } }, error: function (xhr, type, errorThrown) { } }); }) } function getImgMore(obj) { layui.use(['jquery'], function () { let $ = layui.jquery let html = ''; let pageBtn = ''; let id = $(obj).attr('data-id'); $.ajax('/manager/file/list', { data: { type: 'img', page: fwqpage, size: 20 }, headers: { 'X-CSRF-TOKEN': _token }, dataType: 'json',//服务器返回json格式数据 type: 'post',//HTTP请求类型 timeout: 10000,//超时时间设置为10秒; success: function (data) { if (data.code == 0) { if (data.data.length > 0) { $.each(data.data, function (i, item) { html += '<span><img src="' + item.src + '" onclick="window.wangEditor.fullscreen.charu(this)"></span>' }) $('#' + id).closest('.editor').find('.w-e-serverImgs .top-box').append(html) if (data.data.length < 20) { pageBtn = '没有了'; $('#' + id).closest('.editor').find('.w-e-serverImgs .lower-box').html(pageBtn) } else { fwqpage++ } } else { layer.msg(data.msg) } } }, error: function (xhr, type, errorThrown) { } }); }) } var sel, range; var textContent; function getblur() { layui.use(['jquery'], function () { let $ = layui.jquery $('.editor .w-e-text').click(function () { sel = window.getSelection(); range = sel.getRangeAt(0); //range.deleteContents(); }) }) } function insertHtmlAtCaret(html, obj) { layui.use(['jquery'], function () { let $ = layui.jquery if (window.getSelection) { // IE9 and non-IE if (sel != undefined) { if (sel.getRangeAt && sel.rangeCount) { var el = document.createElement("div"); el.innerHTML = html; var frag = document.createDocumentFragment(), node, lastNode; while ((node = el.firstChild)) { lastNode = frag.appendChild(node); } range.insertNode(frag); // Preserve the selection if (lastNode) { range = range.cloneRange(); range.setStartAfter(lastNode); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); } } } else { $(obj).append(html) } } else if (document.selection && document.selection.type != "Control") { // IE < 9 document.selection.createRange().pasteHTML(html); } textContent = $(obj).html();//这个也很重要。因为如果不写可能就会覆盖了原来内容替换成你添加的。或者是干脆不显示了。textContent是全局变量是你输入的内容。 $(obj).closest('.editor').parent().find('textarea').val(textContent) }) } function limitContentLength(elm, len) { layui.use(['jquery'], function () { let $ = layui.jquery var newString = $(elm).val().slice(0, len); $(elm).val(newString); }) } /** * 弹窗重新渲染的内容 * @param filter lay-filter * @param iconName 图标名称,自动识别fontClass/unicode */ function alertRender() { layui.use(['jquery', 'form', 'iconPickerFa'], function () { var form = layui.form, iconPicker = layui.iconPickerFa, $ = layui.jquery form.render(); iconPicker.render({ // 选择器,推荐使用input elem: '#iconPicker', // 数据类型:fontClass/unicode,推荐使用fontClass type: 'fontClass', // 是否开启搜索:true/false search: true, // 是否开启分页 page: true, // 每页显示数量,默认12 limit: 12, // 点击回调 click: function (data) { }, // 渲染成功后的回调 success: function (d) { $('#iconPicker').val('iconpicker'); } }); var iconStr = $('#iconPicker').val(); if (iconStr) { iconPicker.checkIcon('iconPicker', iconStr); } else { iconPicker.checkIcon('iconPicker', 'layui-icon-star-fill'); } }) layui.use(['jquery'], function () { let $ = layui.jquery setTimeout(function () { $(window).trigger("resize"); }, 100) }) } //打开弹出层 function openLayer(url, title, width = '100%', height = '100%') { layui.use(['jquery', 'layer'], function () { let $ = layui.jquery, layer = layui.layer; let index = layer.open({ title: title, type: 2, shade: 0.2, maxmin: true, shadeClose: true, area: [width, height], content: url, }); $(window).on("resize", function () { layer.full(index); }); }) } //删除行 function delRow(url, ids, instance, msg) { layui.use(['jquery', 'layer'], function () { let $ = layui.jquery, layer = layui.layer; msg = (msg === null || msg === undefined) ? '确认删除吗?' : msg; let index = layer.confirm(msg, { btn: ['确认', '取消'], //按钮 title: '操作提示', }, function () { $.post(url, {ids: ids}, function (res) { layer.close(index) layer.msg(res.msg) if (res.code === 0) { instance.reload(); } }) }, function () { layer.close(index) return false; }); }) } // 刷新Tab function refreshTab(insTb) { insTb.reload(); } // 获取文件访问路径 function getFileRequestUrl(url) { let ele = document.getElementById('fileDomain'); let fileDomain = ''; if (ele) { fileDomain = ele.getAttribute('data-oss'); } if (url !== undefined && url.length > 4) { let prefix = url.substr(0, 4); if (prefix === 'http') { return url; } else { return fileDomain + url; } } else { return url; } } /** * 和PHP一样的时间戳格式化函数 * @param {string} format 格式 * @param {int} timestamp 要格式化的时间 默认为当前时间 (10位数) * @return {string} 格式化的时间字符串 */ function date(format, timestamp){ var jsdate=((timestamp) ? new Date(timestamp*1000) : new Date()); var pad = function(n, c){ if((n = n + "").length < c){ return new Array(++c - n.length).join("0") + n; } else { return n; } }; var txt_weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; var txt_ordin = {1:"st", 2:"nd", 3:"rd", 21:"st", 22:"nd", 23:"rd", 31:"st"}; var txt_months = ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; var f = { // Day d: function(){return pad(f.j(), 2)}, D: function(){return f.l().substr(0,3)}, j: function(){return jsdate.getDate()}, l: function(){return txt_weekdays[f.w()]}, N: function(){return f.w() + 1}, S: function(){return txt_ordin[f.j()] ? txt_ordin[f.j()] : 'th'}, w: function(){return jsdate.getDay()}, z: function(){return (jsdate - new Date(jsdate.getFullYear() + "/1/1")) / 864e5 >> 0}, // Week W: function(){ var a = f.z(), b = 364 + f.L() - a; var nd2, nd = (new Date(jsdate.getFullYear() + "/1/1").getDay() || 7) - 1; if(b <= 2 && ((jsdate.getDay() || 7) - 1) <= 2 - b){ return 1; } else{ if(a <= 2 && nd >= 4 && a >= (6 - nd)){ nd2 = new Date(jsdate.getFullYear() - 1 + "/12/31"); return date("W", Math.round(nd2.getTime()/1000)); } else{ return (1 + (nd <= 3 ? ((a + nd) / 7) : (a - (7 - nd)) / 7) >> 0); } } }, // Month F: function(){return txt_months[f.n()]}, m: function(){return pad(f.n(), 2)}, M: function(){return f.F().substr(0,3)}, n: function(){return jsdate.getMonth() + 1}, t: function(){ var n; if( (n = jsdate.getMonth() + 1) == 2 ){ return 28 + f.L(); } else{ if( n & 1 && n < 8 || !(n & 1) && n > 7 ){ return 31; } else{ return 30; } } }, // Year L: function(){var y = f.Y();return (!(y & 3) && (y % 1e2 || !(y % 4e2))) ? 1 : 0}, //o not supported yet Y: function(){return jsdate.getFullYear()}, y: function(){return (jsdate.getFullYear() + "").slice(2)}, // Time a: function(){return jsdate.getHours() > 11 ? "pm" : "am"}, A: function(){return f.a().toUpperCase()}, B: function(){ // peter paul koch: var off = (jsdate.getTimezoneOffset() + 60)*60; var theSeconds = (jsdate.getHours() * 3600) + (jsdate.getMinutes() * 60) + jsdate.getSeconds() + off; var beat = Math.floor(theSeconds/86.4); if (beat > 1000) beat -= 1000; if (beat < 0) beat += 1000; if ((String(beat)).length == 1) beat = "00"+beat; if ((String(beat)).length == 2) beat = "0"+beat; return beat; }, g: function(){return jsdate.getHours() % 12 || 12}, G: function(){return jsdate.getHours()}, h: function(){return pad(f.g(), 2)}, H: function(){return pad(jsdate.getHours(), 2)}, i: function(){return pad(jsdate.getMinutes(), 2)}, s: function(){return pad(jsdate.getSeconds(), 2)}, //u not supported yet // Timezone //e not supported yet //I not supported yet O: function(){ var t = pad(Math.abs(jsdate.getTimezoneOffset()/60*100), 4); if (jsdate.getTimezoneOffset() > 0) t = "-" + t; else t = "+" + t; return t; }, P: function(){var O = f.O();return (O.substr(0, 3) + ":" + O.substr(3, 2))}, //T not supported yet //Z not supported yet // Full Date/Time c: function(){return f.Y() + "-" + f.m() + "-" + f.d() + "T" + f.h() + ":" + f.i() + ":" + f.s() + f.P()}, //r not supported yet U: function(){return Math.round(jsdate.getTime()/1000)} }; return format.replace(/[\]?[a-zA-Z]/g, function(t){ let ret = ''; if (f[t]) { ret = f[t](); } return ret; }); } function refreshBtn() { layui.use(['jquery'], function () { let $ = layui.jquery; $('[data-table-refresh]').trigger("click"); }) }