hm-react-cli
Version:
Create a Huimei React project by module
1,192 lines (1,132 loc) • 33.9 kB
JavaScript
/*
* @Author: houzhenyu
* @Date: 2019-03-20 17:49:39
* @Last Modified by: limeizhen
* @Last Modified time: 2019-09-05 17:54:33
*/
$.fn.extend({
/**
* art-template
* @param path 模板路径
* @param data 模板中用到的数据
* @param callback 处理完模板回调(callbck 中this为当前 dom 对象;注:模板中的事件必需在回调中完成绑定)
*/
getTemplateFn: function (path, data, callback, res, opt) {
var _this = this;
opt = opt || {};
$.ajax({
type: 'GET',
url: path,
timeout: 35000, //超时时间设置,单位毫秒
dataType: 'html',
contentType: 'application/json; charset=utf-8',
success: function (htmlText) {
var html = '';
try {
var render = template.compile(htmlText);
$[path] = render; // 把解析方法存在 $.__proto__
html = render(data || {});
} catch (error) {
console.log(error);
}
if (opt.beforeMouned) {
html = opt.beforeMouned(html);
}
_this.html(html);
// 模板加载完成通知回调
callback && callback.call(_this);
res(_this);
},
complete: function (XMLHttpRequest, status) {
//请求完成后最终执行参数
if (status == 'timeout') {
// alert('art-template ' + path + ' time out!');
}
},
error: function (res) {},
});
},
myResize: function (fn, id) {
const event = 'resize';
const eId = '.' + id;
const resize = () => {
$(window).off(eId);
fn && fn();
setTimeout(() => $(window).on(event + eId, resize), 0);
};
$(window).on(event + eId, resize);
},
/**
* 获取art-template模板函数,之后可以复用,不用每次渲染每次都获取
* @param path 模板路径
* @param callback 获取完模板函数后的回调
*/
getTemplateFn2: function (path, callback) {
var _this = this;
// 加载模板
$.ajax({
type: 'GET',
url: path,
timeout: 15000, //超时时间设置,单位毫秒
dataType: 'html',
contentType: 'application/json; charset=utf-8',
success: function (htmlText) {
var html = '';
try {
var render = template.compile(htmlText);
// html = render(data || {});
} catch (error) {
alert('art-template template.render() error!');
}
//_this.html(html);
// 模板加载完成通知回调
callback && callback(render);
},
complete: function (XMLHttpRequest, status) {
//请求完成后最终执行参数
if (status == 'timeout') {
alert('art-template ' + path + ' time out!');
}
},
error: function (res) {
alert('art-template request error!');
},
});
// return this;
},
/**
* ie8/9不兼容placeholder属性的替代方法
*/
bind_placeholder: function () {
$(document)
.on('focus', '.drop-down-query', function () {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
})
.on('blur', '.drop-down-query', function () {
var input = $(this);
var placeholderTxt = input.attr('placeholder');
if (input.val() == '' || input.val() == placeholderTxt) {
input.addClass('placeholder');
input.val(placeholderTxt);
}
});
},
/**
* art-template
* @param path 模板路径
* @param data 模板中用到的数据
* @param callback 处理完模板回调(callbck 中this为当前 dom 对象;注:模板中的事件必需在回调中完成绑定)
* @param opt
*/
render: function (path, data, callback, opt) {
var _this = this;
opt = opt || {};
// 加载模板
return new Promise(function (res, rect) {
if ($[path]) {
var html = '';
try {
var renderFn = $[path];
html = renderFn(data || {});
} catch (error) {
console.log(error);
}
if (opt.beforeMouned) {
html = opt.beforeMouned(html);
}
// 放在任务队列最后面执行
setTimeout(function () {
_this.html(html);
// 模板加载完成通知回调
callback && callback.call(_this);
res(this);
}, 0);
} else {
$.fn.getTemplateFn.call(_this, path, data, callback, res, opt);
}
});
},
/**
*
* 异常提示
* @param msg 异常提示语
* @param time 提示时间毫秒,缺省3000
* @param type 类型,俩种异常类型(success,error,info,warning)
*/
toast: function (msg, type, time) {
var _this = this;
// 防止重复生成提示框
if ($('#toast-container').length) {
$('#toast-container').remove();
}
// 清楚定时器
if (window._iToastTimerIndex) {
clearTimeout(window._iToastTimerIndex);
}
// 提示内容
_this.append("<div class='toast-container toast-" + (type || 'success') + "' id='toast-container'>" + msg + '</div>');
// 缺省3秒后提示消失
window._iToastTimerIndex = setTimeout(function () {
$('#toast-container').fadeOut(300, function () {
$('#toast-container').remove();
});
}, time || 3000);
},
/**
* 排序样式处理
* @param {*} descCallback 降序
* @param {*} ascCallback 升序
*/
sortTableHandler: function (descCallback, ascCallback) {
// 获取当前排序ICON样式
var isdesc = this.attr('class');
// 根据状态显示排序标签 ICON
if (isdesc && isdesc.indexOf('fa-long-arrow-up') != -1) {
// 降序
this.removeClass('fa-long-arrow-up');
this.addClass('fa-long-arrow-down');
descCallback && descCallback(this);
} else {
// 升序
this.removeClass('fa-long-arrow-down');
this.addClass('fa-long-arrow-up');
ascCallback && ascCallback(this);
}
// 显示
this.show();
},
});
/**
* 静态扩展
*/
$.extend({
/**
* 跳转到指定页面
* @param {*} path
*/
go: function (path) {
window.location.href = path;
},
/**
* 根据 hash 路由跳转(注:兼容 IE8+及主流浏览器)
* 重复添加相同的path会被覆盖
* @param {*} path 路由地址(注:*为缺省路由)
* @param {*} callback 回调方法(注:不存在回调,跳转新路由 )
* @param callback(param) param 路由参数
*/
router: function (el) {
var _this = this;
// 只创建一次监听
if (!window.isInstalledRouter) {
$(document).ready(xevent);
$(window).on('hashchange', xevent);
/**
* 监听 url 中 hash 变化
*/
function xevent() {
// 从 url 中获取 hash
var curr_path = window.location.hash.substring(1) || '/';
// start.
fire(curr_path);
// 增加外部监听路由变化
_this.onRouterListener && _this.onRouterListener(curr_path);
}
/**
* 解析路由并执行回调方法
* @param {*} xpath
*/
function fire(xpath) {
var p = fx(xpath);
var params = {},
hasMatch = false,
currUrl = '';
for (var t in HMContext.controllerMap) {
var m = fx(t);
if (m.modelPrefix == p.modelPrefix) {
hasMatch = true;
currUrl = HMContext.controllerMap[t];
for (var i = p.modelPrefixLen; i < p.length; i++) {
params[m.items[i].replace(/^:/, '')] = p.items[i].replace(/^:/, '');
}
break;
}
}
if (!hasMatch) {
return;
}
// 从路由仓库中查找当前 path 对应的 model
if (typeof HMContext.modules[p.modelPrefix] === 'undefined') {
$LAB.script('./js/' + currUrl).wait(function () {
var currentAction = new HMContext.modules[p.modelPrefix]({
el: $(el),
params: params,
});
// Common.controllers[p.modelPrefix] = currentAction;
});
} else {
var currentAction = new HMContext.modules[p.modelPrefix]({
el: $(el),
params: params,
});
// HMContext.HmControlls[p.modelPrefix] = currentAction;
}
return;
}
/**
* 路由 model 和 path 解析器
* @param {*} path
*/
function fx(path) {
var ms = path.split('/');
var prefix = ms[0];
var len = ms.length;
var modelPrefix = '';
// 获取路由模型固定前缀
if (path.indexOf('/:') != -1) {
modelPrefix = path.split('/:')[0];
} else {
modelPrefix = path;
}
return {
items: ms,
prefix: prefix,
length: len,
modelPrefix: modelPrefix,
modelPrefixLen: modelPrefix.split('/').length,
};
}
// 事件监听锁
window.isInstalledRouter = true;
// 路由仓库
}
// 将路由注册到仓库中
// 重复添加会被覆盖
},
/**
* 路由跳转
* @param {*} action
*/
redirect: function (action) {
window.location.hash = action;
},
/**
* 浏览器版本校验
*/
browserCheck: function () {
// 判断是否兼容
var ieVersion = '';
var theUA = window.navigator.userAgent.toLowerCase();
if (
(theUA.match(/msie\s\d+/) && theUA.match(/msie\s\d+/)[0]) ||
(theUA.match(/trident\s?\d+/) && theUA.match(/trident\s?\d+/)[0])
) {
ieVersion = theUA.match(/msie\s\d+/)[0].match(/\d+/)[0] || theUA.match(/trident\s?\d+/)[0];
}
return ieVersion;
},
/**
* 获取当前路由信息
*/
getRouter: function () {
return window.iCurrentRouterEntity || {};
},
/**
* ajax 请求
* @param opt 请求参数
*/
axios: function (opt) {
var url = opt.url;
var type = opt.type || 'POST';
var success = opt.success;
var error = opt.error;
var timeout = opt.timeout;
var loading = opt.loading ===undefined? true:opt.loading;
//如果请求为json文件,请求方法为GET
if (url.match('.json')) {
type = 'GET';
}
opt.data === undefined && opt.type === ''? undefined: opt.data || {};
//全局添加的loading走这个逻辑
if (!opt.htmlBox) {
//全局变量axiosList,缓存请求url
if (!window.axiosList) {
window.axiosList = [];
}
window.axiosList.push(url);
}
loading && $.LightBox.show(opt.htmlBox);
const isNodeApi = /^\//.test(url);
if (!window.XDomainRequest || isNodeApi) {
$.ajax({
type: type,
url: url,
timeout: timeout||15000, //超时时间设置,单位毫秒
data: JSON.stringify(opt.data),
headers: opt.header,
dataType: opt.dataType || 'json',
contentType: opt.contentType || 'application/json; charset=utf-8',
beforeSend() {
const curPath = location.pathname;
const inIframe = window.self !== window.top;
if (opt.beforeSend || curPath === '/' || curPath === '/login/index.html' || inIframe) return;
const res = $.getCookieInfo('userInfo');
if (res) {
$.axios({
url: '/manage/checkUser',
data: {},
beforeSend() {},
success: (res) => {},
error: (error) => {},
});
}
},
success: function (res) {
//全局添加的loading
if (!opt.htmlBox) {
if ($.isCompltedRequest(url)) {
//当请求列表为空时,即所有的请求都完成后,关闭loading
loading && $.LightBox.hide(opt.htmlBox);
}
} else {
//布局添加的loading
loading && $.LightBox.hide(opt.htmlBox);
}
try {
var head = res.head;
if (head && head.error !== 0) {
error.call(this, res);
return $('body').toast(head.message, 'error');
} else if (res.msg && res.code !== 200) {
return $('body').toast(res.msg, 'error');
}
success && success.call(this, res);
} catch (e) {
$('body').toast('系统' + e + '异常', 'error');
}
},
complete: function (XMLHttpRequest, status) {
//请求完成后最终执行参数
if (status == 'timeout') {
loading && $.LightBox.hide(opt.htmlBox);
window.axiosList = [];
}
},
error: function (res) {
loading && $.LightBox.hide(opt.htmlBox);
window.axiosList = [];
var rs = res.responseText;
if (rs) {
try {
rs = JSON.parse(rs);
// 跳转到登录
const curPath = location.pathname;
if (rs.code == 401 && (curPath !== '/' || curPath !== '/login/index.html')) {
$.go('/');
}
const msg = (rs.head && rs.head.message) || rs.msg;
$('body').toast(msg, 'error');
} catch (e) {
console.log(e);
$('body').toast('系统' + res.status + '异常', 'error');
}
} else {
$('body').toast('接口异常请稍后再试', 'error');
}
error && error.call(this, res);
},
});
} else {
//IE8.0 跨域
var infoParam = {};
if (opt.header) {
infoParam['api-extend-params'] = opt.header['api-extend-params'];
infoParam['Huimei_id'] = opt.header['Huimei_id'];
infoParam = JSON.stringify(infoParam);
infoParam = encodeURIComponent(infoParam);
} else {
infoParam = '';
}
const _t = this;
_t.xdr({
time: 10000,
type: type,
url: url + '?_hm=' + infoParam,
data: opt.data ? JSON.stringify(opt.data) : '',
beforeSend() {
const curPath = location.pathname;
const inIframe = window.self !== window.top;
if (opt.beforeSend || curPath === '/' || curPath === '/login/index.html' || inIframe) return;
const res = $.getCookieInfo('userInfo');
if (res) {
$.axios({
url: '/manage/checkUser',
data: {},
beforeSend() {},
});
}
},
success: function (res) {
//全局添加的loading
if (!opt.htmlBox) {
if ($.isCompltedRequest(url)) {
//当请求列表为空时,即所有的请求都完成后,关闭loading
loading && $.LightBox.hide(opt.htmlBox);
}
} else {
//布局添加的loading
loading && $.LightBox.hide(opt.htmlBox);
}
try {
if (typeof res === 'string') {
res = JSON.parse(res);
}
var head = res.head;
if (head && head.error !== 0) {
error.call(this, res);
return $('body').toast(head.message, 'error');
} else if (res.msg && res.code !== 200) {
return $('body').toast(res.msg, 'error');
}
success && success.call(this, res);
} catch (e) {
$('body').toast('系统' + e + '异常', 'error');
}
},
complete: function (XMLHttpRequest, status) {
//请求完成后最终执行参数
if (status == 'timeout') {
loading &&$.LightBox.hide(opt.htmlBox);
window.axiosList = [];
}
},
error: function (res) {
loading && $.LightBox.hide(opt.htmlBox);
window.axiosList = [];
var rs = res.responseText;
if (rs) {
try {
rs = JSON.parse(rs);
// 跳转到登录
const curPath = location.pathname;
if (rs.code == 401 && (curPath !== '/' || curPath !== '/login/index.html')) {
$.go('/');
}
const msg = (rs.head && rs.head.message) || rs.msg;
$('body').toast(msg, 'error');
} catch (e) {
$('body').toast('系统' + res.status + '异常', 'error');
}
} else {
$('body').toast('接口异常请稍后再试', 'error');
}
error && error.call(this, res);
},
});
}
},
xdr: function (opt) {
var xdr;
function alert_timeout() {
// var error = new Error('xdr time out');
// throw error;
}
function alert_progress() {
// alert("XDR onprogress");
}
/*
* 请求
* @param url 请求url
* @param metch 请求方法
* @param data 请求参数字符串
* @param time 请求超时
*/
function req_init(url, metch, time, data, callback, errCalback, beforeSend) {
var timeout = time || 10000;
if (window.XDomainRequest) {
// Check whether the browser supports XDR.
xdr = new XDomainRequest(); // Create a new XDR object.
if (xdr) {
// There is an error and the request cannot be completed.
// For example, the network is not available.
xdr.onerror = function () {
errCalback && errCalback(xdr);
};
// This event is raised when the request reaches its timeout.
xdr.ontimeout = alert_timeout;
// When the object starts returning data, the onprogress event
// is raised and the data can be retrieved by using responseText.
xdr.onprogress = alert_progress;
// When the object is complete, the onload event is raised and
// the responseText ensures the data is available.
xdr.onload = function () {
callback && callback(xdr.responseText);
};
beforeSend && beforeSend();
xdr.timeout = timeout;
// The URL is preset in the text area. This is passed in the
// open call with a get request.
xdr.open(metch || 'GET', url);
// The request is then sent to the server.
xdr.send(data);
} else {
// alert('Failed to create new XDR object.');
}
} else {
// alert('XDR does not exist.');
}
}
//初始化入口
req_init(opt.url, opt.type, opt.time, opt.data, opt.success, opt.error, opt.beforeSend);
},
/**
* @description: 判断页面中的请求是否都已经完成
* @return: boolean 请求列表是否为空 为空则所有请求完成
*/
isCompltedRequest: function (url) {
window.axiosList || (window.axiosList = []);
for (var i = 0; i < window.axiosList.length; i++) {
if (window.axiosList[i] === url);
window.axiosList.splice(i, 1);
}
return !window.axiosList.length;
},
/**
* url参数获取
*/
queryUrlParam: function (name) {
var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
var r = window.location.search.substr(1).match(reg);
if (r !== null) return decodeURIComponent(r[2]);
return null;
},
/**
* url参数获取
*/
queryHrefUrlParam: function () {
var qs;
if (window.location.hash) {
var p = window.location.hash.indexOf('?');
qs = window.location.hash.substr(p);
} else {
qs = window.location.search;
}
if (!qs) return {};
if (qs[0] === '?') qs = qs.slice(1);
var pairs = qs.split('&');
if (!pairs || pairs.length === 0) return {};
return pairs.reduce(function (params, p) {
var idx = p.indexOf('=');
// 排除 react-router 的 `_k`
if (p.slice(0, idx) === '_k') return params;
if (idx > 0) {
params[p.slice(0, idx)] = decodeURIComponent(p.slice(idx + 1));
}
return params;
}, {});
},
/**
* 对日期进行格式化,
* @param date 要格式化的日期
* @param format 进行格式化的模式字符串
* 支持的模式字母有:
* y:年,
* M:年中的月份(1-12),
* d:月份中的天(1-31),
* h:小时(0-23),
* m:分(0-59),
* s:秒(0-59),
* S:毫秒(0-999),
* q:季度(1-4)
*/
timestamp: function (date, format) {
date = new Date(date);
var map = {
M: date.getMonth() + 1, //月份
d: date.getDate(), //日
h: date.getHours(), //小时
m: date.getMinutes(), //分
s: date.getSeconds(), //秒
q: Math.floor((date.getMonth() + 3) / 3), //季度
S: date.getMilliseconds(), //毫秒
};
format = format.replace(/([yMdhmsqS])+/g, function (all, t) {
var v = map[t];
if (v !== undefined) {
if (all.length > 1) {
v = '0' + v;
v = v.substr(v.length - 2);
}
return v;
} else if (t === 'y') {
return (date.getFullYear() + '').substr(4 - all.length);
}
return all;
});
return format;
},
//loading 加载
LightBox: {
element: null,
init: function (box) {
var height = '100%';
var position = box ? 'absolute' : 'fixed';
var marginTop = box ? '200px' : '320px';
var zindex = box ? '1000005' : '100000005';
var html =
'<div class="lightbox" style="left:0; top:0; width:100%; height:' +
height +
';zoom:1; position:' +
position +
'; z-index:' +
zindex +
'; " ><img src="/assets/images/loading.gif" style="margin-left: 48%; filter:alpha(opacity=20); -moz-opacity: 0.2; opacity: 0.2;margin-top:' +
marginTop +
'" /></div>';
if (box) {
this.element = $(html).appendTo(box);
} else {
this.element = $(html).appendTo(document.body);
}
this.count = 0;
},
show: function (box) {
this.init(box);
this.count++;
},
hide: function (box) {
this.count--;
if (box) {
$(box).find('.lightbox').remove();
} else {
$(document.body).find('.lightbox').remove();
}
if (this.count == 0) {
this.element.remove();
}
},
},
/**
* 弹出窗
*/
modalBox: {
element: [],
count: 0,
init: function (name, style) {
style = style || {};
var element = null;
var height = '',
html = '',
width = '',
childZ = '',
le = '',
_top = '';
if (name) {
//正常居中的堂客
height = (style && style.high) || 'auto';
width = (style && style.wide) || '60';
le = (100 - width) / 2;
_top = 320;
if (style && style.top) {
_top = 320 - style.top;
}
childZ = this.count + 1;
var hasClose = style.hasClose
html =
'<div class="modalBox" style="left:0; opacity: 0.5; filter:Alpha(opacity=50); background: #555555; top:0; width:100%; height:100%;zoom:1; position:fixed; z-index:1000000' +
childZ +
'" ></div>' +
'<div id="modalBox" class="modal-con ' +
style.className +
'"' +
'style="width: ' +
width +
'%;min-width:550px;height:' +
height +
';border-radius: 4px;position: fixed;text-align: center;color: #fff;line-height: 35px;left:' +
le +
'%;top: 50%;margin-top:-' +
_top +
'px;z-index:1000000' +
childZ +
'">' +
'<div class="modal-con-top" style="position: relative; background:#4A90E2;height:40px;border-radius: 4px 4px 0 0;line-height:40px;">'+
'<span>' + name +'</span> '+
(hasClose ?'<div class="close-pic"><img src="../../assets/images/close.png" alt=""></div>' :'')+
'</div>' +
'<div style="background: #4A90E2; padding: 0 5px 5px 5px; border-radius: 0 0 4px 4px;"><div class="modal-con-data" style="min-height:200px;background:#fff; padding: 4px; border-radius: 4px"></div></div></div>';
} else {
height = $(window).height() - 35 - 120;
width = (style && style.wide) || '60';
le = (100 - width) / 2;
_top = 320;
if (style && style.top) {
_top = 320 - style.top;
}
childZ = this.count + 1;
html =
'<div style="left:0;opacity: 0.2; filter:Alpha(opacity=20); background: #555555; top:0; width:100%; height:100%;zoom:1; position:fixed; z-index:1000000' +
this.count +
';" class="modalBox ' +
(style.className || '') +
'" ></div>' +
'<div class="modal-con" id="modalBox" style="width: ' +
width +
'%;min-width:740px;border-radius: 4px;position: fixed;overflow:auto;line-height: 35px;right:-60%;top:60px;margin-top:0px;z-index:1000000' +
childZ +
'">' +
'<div class="modal-con-top" style="position: relative; background:#fff4f0;border-bottom:1px solid #e8d7cf;height:40px;border-radius: 4px 4px 0 0;line-height:40px;"><div class="top-detaild"></div></div>' +
'<div style="background: #4A90E2; padding: 0 5px 5px 5px; border-radius: 0 0 4px 4px;"><div class="modal-con-data " style="height:' +
height +
'px;min-height:200px;overflow: auto;background:#fff; border-radius: 4px; padding: 4px; "></div><div class="modal-con-btom" style="height:60px;background:#fff" ></div></div></div>';
}
element = $(html).appendTo(document.body);
this.element.push(element);
$('body').css({
overflow: 'hidden',
});
return element;
},
show: function (name, style) {
return this.init(name, style);
},
hide: function () {
this.element.forEach(function (item) {
item.remove();
});
$('body').css({
overflow: 'auto',
});
},
},
/**
* 弹出窗
*/
modalSmall: {
element: [],
successFn: null,
count: 0,
init: function (name, style) {
var _t = this;
style = style || {};
var element = null;
var height = '',
html = '',
width = '',
childZ = '',
le = '',
_top = '';
if (name) {
//正常居中的堂客
height = (style && style.high) || 'auto';
width = (style && style.wide) || '60';
le = (100 - width) / 2;
_top = 320;
if (style && style.top) {
_top = 320 - style.top;
}
childZ = this.count + 1;
html =
'<div class="modalBox" style="left:0; opacity: 0.5; filter:Alpha(opacity=50); background: #555555; top:0; width:100%; height:100%;zoom:1; position:fixed; z-index:1000000' +
childZ +
'" ></div>' +
'<div id="modalSmall" class="modal-con ' +
style.className +
'"' +
'style="width: 500px;min-width:300px;height:' +
height +
';border-radius: 4px;position: fixed;text-align: center;color: #fff;line-height: 35px;left:' +
le +
'%;top: 50%;margin-top:-' +
_top +
'px;z-index:1000000' +
childZ +
'">' +
'<div class="modal-con-data" style="min-height:160px;background:#fff;border-radius: 4px;"></div></div>';
} else {
modalId = style.modalId || 'modalBox_right';
modalBoxId = style.modalBox || "modalBox_rightBox";
height = $(window).height() - 35 - 60 - 20;
width = style && style.wide || '60';
le = (100 - width) / 2;
_top = 320;
if (style && style.top) {
_top = 320 - style.top;
}
childZ = this.count + 1;
html = '<div class="modalBox rightBox" id="' + modalBoxId + '" style="left:0;opacity: 0.2; filter:Alpha(opacity=20); top:0; width:100%; height:100%;zoom:1; position:fixed; z-index:9' + this.count + '; " ></div>' +
'<div class="modal-con" id="' + modalId + '" style="width: 500px;min-width:400px;position: fixed;overflow:auto;line-height: 35px;right:-100%;top:0px;bottom: 0; margin-top:0px;z-index:9999; overflow: hidden; box-shadow: 0px 0px 16px #044188;">' +
'<div class="modal-body" style="width:100%;height:100%;background:#eeeff4;">' +
'<div class="modal-con-top" style="position: relative; background:#fffbfa;min-height:0px;line-height:0px;">' +
'<div class="top-detaild"></div>' +
'<a class="rightClose" style="display:none;position: absolute;right:10px;top:0; color:#fff;cursor: pointer;width: 12px;height: 40px;background:url(/assets/images/close.png) no-repeat center; "></a>' +
'</div>' +
'<div class="modal-con-data" style="height: 100%;min-height:200px;background:#fff;position:relative;padding:0px;">' +
'</div>' +
'</div>' +
'</div>';
}
element = $(html).appendTo(document.body);
this.element.push(element);
$('body').css({
overflow: 'hidden',
});
$(':focus').blur();
$('body')
.off('keydown.modal')
.on('keydown.modal', function (e) {
if (e.keyCode === 13) {
_t.successFn && _t.successFn();
}
if (e.keyCode === 27) {
_t.hide();
}
});
return this;
},
show: function (name, style) {
return this.init(name, style);
},
hide: function () {
this.element.forEach(function (item) {
item.remove();
});
$('body').css({
overflow: 'auto',
});
},
// hide: function () {
// this.element.forEach(function (item) {
// item.remove();
// });
// $('body').off('keydown.modal');
// this.successFn = null;
// // $('body').css({
// // overflow: 'auto',
// // });
// },
},
/**
* 设置cook里的值
* @param {*} name
* @param {*} value
* @param {*} day
*/
setCookie: function (name, value, day) {
var Days = day || 0.5;
var exp = new Date();
exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
document.cookie = name + '=' + escape(value) + ';path=/';
},
/**
* 从cookie获取信息
* @param name
* @returns {*}
*/
getCookieInfo: function (name) {
var cookieArray = document.cookie.split('; ');
var cookie = {};
for (var i = 0; i < cookieArray.length; i++) {
var arr = cookieArray[i].split('=');
if (arr[0] == name) return unescape(arr[1]);
}
return '';
},
getCustomerId: function (name) {
var userInfo = $.getCookieInfo('userInfo');
var obj = JSON.parse(userInfo || '{}');
return obj.customer_id;
},
getMaysonUrl() {
var userInfo = JSON.parse($.getCookieInfo('userInfo') || null) || {};
var mayson_url = userInfo.mayson_url;
const inIframe = window.self !== window.top;
if (!mayson_url && !inIframe) {
return $.go('/');
}
return mayson_url;
},
getAutherKey() {
var userInfo = JSON.parse($.getCookieInfo('userInfo') || null) || {};
var auther_key = userInfo.auther_key;
const inIframe = window.self !== window.top;
if (!auther_key && !inIframe) {
return $.go('/');
}
return auther_key;
},
phodlerHolder: function () {
$('input[holder]').each(function () {
if ($(this).parent().find('.phodler').length == 0) {
$(this)
.parent()
.css({
position: 'relative',
})
.append('<span class="phodler">' + $(this).attr('holder') + '</span>');
}
});
$('.phodler').click(function () {
$(this).parent().find('input[holder]').focus();
});
},
fillPhodlerHolder: function () {
$('input[holder]').each(function () {
if ($(this).parent().find('.fill-phodler').length == 0) {
$(this)
.parent()
.css({
position: 'relative',
})
.append('<span class="fill-phodler">' + $(this).attr('holder') + '</span>');
}
});
$('.fill-phodler').click(function () {
$(this).parent().find('input[holder]').focus();
});
},
/**
* 提示信息
* @param type 信息类型:error/success/info/warning defualt为‘success’
* @param message 提示文字 defualt为‘成功’
* @param timeout 时间间隔,多长时间后提示消失 default为‘3s’
*/
createMessage: function (type, message, timeout, callback) {
var html = '<p class="tip_message ' + (type || 'success') + '">' + (message || '成功') + '</p>';
var tip_message = null;
var targetBody = $(window.top.document.body);
targetBody.append(html);
tip_message = targetBody.find('.tip_message');
setTimeout(function () {
if (tip_message.length) {
tip_message.fadeOut(800);
}
typeof callback == 'function' && callback();
}, timeout || 500);
},
/**
* 获取随机数
* @param {*} i
*/
getUUId(i) {
let d = new Date(),
rand = parseInt(Math.random() * 1000);
return d.getTime().toString(36) + rand.toString(36) + (i || '');
},
getWidth: function (v) {
var width = '100%';
if (v && v.indexOf('/') != -1) {
var wlist = v.split('/');
var molecule = wlist[0]; // 分子
var denominator = wlist[1]; // 分母
width = Math.floor((molecule / denominator) * 10000)/100+ '%';
}
return width;
},
/**
* 初始化日期控件
* @param {*} eleName 日期目标元素名称
*/
initLaydate: function (data) {
var options = $.getLaydateOptions(data);
return laydate.render(options);
},
/**
* 根据目标元素名称,获取laydate参数
* @param {*} eleName 日期目标元素名称
*/
getLaydateOptions: function (data) {
var elem = "#" + data.eleName;
var options = { //渲染开始时间选择
elem: elem, //通过id绑定html中插入的start
type: data.type ? data.type : 'date',
max: moment().format('YYYY-MM-DD HH:mm:ss'),
showBottom: false,
ready: function (value, date) {
data.ready && data.ready(value, date);
},
change: function (value, date) { //监听日期被切换
lay(elem).val(value);
data.change && data.change(value, date);
},
done: function (value, date) { //监听日期被切换
lay(elem).val(value);
data.done && data.done(value, date);
}
};
return options;
},
/**
* 根据月份获取对应 月 的开始与结束日期
* @param {*} timeStart 开始月份
* @param {*} timeEnd 结束月份
* @returns
*/
getJumpDate: function (timeStart,timeEnd) {
var _t = this;
var start = moment(timeStart).format('YYYY-M-DD').split('-');
var end = moment(timeEnd).format('YYYY-M-DD').split('-');
var startYear = start[0];
var startMonth = start[1];
var endYear = end[0];
var endMonth = end[1];
var firstDay = new Date(startYear, startMonth - 1, 1);
var lastDay = new Date(endYear, endMonth, 0);
var params = {
timeStart: moment(firstDay).format('YYYY-MM-DD'),
timeEnd: moment(lastDay).format('YYYY-MM-DD')
};
return params;
},
});
$.fn.offset = function (options) {
if (arguments.length) {
return options === undefined
? this
: this.each(function (i) {
jQuery.offset.setOffset(this, options, i);
});
}
var docElem,
win,
box = { top: 0, left: 0 },
elem = this[0],
doc = elem && elem.ownerDocument;
if (!doc) {
return;
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if (!jQuery.contains(docElem, elem)) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if (typeof elem.getBoundingClientRect !== 'undefined') {
box = elem.getBoundingClientRect();
}
win = getWindow(doc);
return {
top: box.top + (win.pageYOffset || docElem.scrollTop || document.body.scrollTop) - (docElem.clientTop || 0),
left: box.left + (win.pageXOffset || docElem.scrollLeft || document.body.scrollLeft) - (docElem.clientLeft || 0),
};
};
function getWindow(elem) {
return jQuery.isWindow(elem) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false;
}
if (!Object.values) {
Object.values = function (obj) {
if (obj !== Object(obj)) throw new TypeError('Object.values called on a non-object');
var val = [],
key;
for (key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
val.push(obj[key]);
}
}
return val;
};
}