JavaScript项目中封装的util常用工具

来源:互联网 发布:最新义乌法院淘宝拍卖 编辑:程序博客网 时间:2024/06/03 14:50
/** * * @authors dongtao * @date    2017-02-20 11:15:01 * @version 1.0.0 * 公有方法 */var utils = utils || {};! function($) {//记录前端日志function webLogs(params) {var cache = common.getLocalStorage('autoClaim.ss.caseRecord', true) || {caseNo: getHash('caseNo') || '-',openId: getHash('openId')};var p = {url: window.location.href || '', //当前页面名称type: 0, //日志类别content: '无内容', //日志内容caseNo: cache.caseNo, //案件号openID: cache.openId //微信唯一编号};if (typeof params === 'string') {p.content = params;} else {$.extend(p, params);}$.post(server() + '/wx/waitAuditing/webLogs', p, function(response) {var res = response;});}//获取当前页面的名称function getPageName() {var pathname = window.location.pathname;var index = pathname.lastIndexOf('\/');if (index > 0) {pathname = pathname.substr(index + 1);}return pathname;}//记录本地日志,用于本地开发和测试function log(msg) {var _d = new Date();var s = _d.getFullYear() + '-' + (_d.getMonth() + 1) + '-' + _d.getDate() + ' ' + _d.getHours() + ':' + _d.getMinutes() + ':' + _d.getSeconds();var _tit = '[' + s + '(' + getPageName() + ')] ' + msg;sessionStorage._mobile_log = (sessionStorage._mobile_log || '') + _tit + '<br/>';webLogs(_tit);console && console.log && console.log(_tit);}//判断是否为undefinedfunction isUndefined(o) {return typeof o === 'undefined';}//判断是否为数组类型function isArray(o) {return o !== null && typeof o === 'object' && 'splice' in o && 'join' in o;}//判断是否为object类型function isObject(o) {return typeof o === 'object';}//判断是否为string类型function isString(o) {return typeof o === 'string';}//判断是否为boolean类型function isBoolean(o) {return typeof o === 'boolean';}//判断对象是否为空字符串,去除前后空格function isBlank(o) {o = o || '';return o === '' || o.trim() === '';}//重定向,页面跳转function redirection(path) {window.location.href = path || '/pages/404.html';}//获取地址栏参数function getHash(key, url) {var hash;if (!!url) {hash = url.replace(/^.*?[#](.+?)(?:\?.+)?$/, "$1");hash = (hash == url) ? "" : hash;} else {hash = self.location.search;}hash = "" + hash;hash = hash.replace(/^[?#]/, '');hash = "&" + hash;var val = hash.match(new RegExp("[\&]" + key + "=([^\&]+)", "i"));if (!val || val.length < 1) {return null;} else {return decodeURIComponent(val[1]);}}//接口地址function server() {return window.location.protocol + '//' + window.location.host + '/cpicclaim_wxh5';}//文件是否存在function isInclude(path) {var index = path.lastIndexOf('\/');var name = index > 0 ? path.substr(index + 1) : path;var css = /css$/i.test(name);var tag = 'link';var pt = 'href';if (!css) {tag = 'script';pt = 'src';}var elements = document.getElementsByTagName(tag);for (var i = 0; i < elements.length; i++) {if (elements[i][pt].indexOf(name) > -1) {return true;}}return false;}//动态加载文件,只能加载CSS和js文件function loadFiles(path, callback, js) {var el = document.getElementsByTagName('body')[0];var node = document.createElement('script');if (js) {node.type = 'text/javascript';node.src = path;} else {el = document.getElementsByTagName('head')[0];node = document.createElement('link');node.rel = 'stylesheet';node.type = 'text/css';node.href = path;}//所有浏览器加载css都会走onload方法node.onload = function() {if (js) {callback({status: true});} else {var _n = 0;var _poll = function(node, callback) {var isLoaded = false;if (/webkit/i.test(navigator.userAgent)) {//webkitif (node.sheet) {isLoaded = true;}} else if (node.sheet) {// for Firefoxtry {if (node.sheet.cssRules) {isLoaded = true;}} catch (ex) {// NS_ERROR_DOM_SECURITY_ERRif (ex.code === 1000) {isLoaded = true;}}}if (isLoaded) {callback({status: true});} else {if (++_n > 10) {callback({status: false,error: 'CSS文件加载失败,请重试...'});} else {window.setTimeout(function() {_poll(node, callback);}, 100);}}};_poll(node, callback);}};node.onerror = function(e) {callback({status: false,error: (js ? 'script' : 'CSS') + '文件加载时发生错误,请重试...'});};el.appendChild(node);}//动态加载css文件function loadStyle(path, callback) {if (!$.isFunction(callback)) return;if (!path || path.length === 0) {callback({status: false,error: '请传入有效的路径'});}var exist = isInclude(path);if (exist) {callback({status: true});} else {loadFiles(path, callback);}}//动态加载js文件function loadScript(path, callback) {if (!$.isFunction(callback)) return;if (!path || path.length === 0) {callback({status: false,error: '请传入有效的路径'});}var exist = isInclude(path);if (exist) {callback({status: true});} else {loadFiles(path, callback, true);}}function getAddress(lat, lang, callback) {var _path = window.location.protocol + '//webapi.amap.com/maps?v=1.3&key=585d5dd703232d5bf2311e7b03882824';loadScript(_path, function(response) {if (response.status) {var n = 0;var t = window.setInterval(function() {n++;if (window.AMap && AMap.service) {window.clearInterval(t);t = null;AMap.service('AMap.Geocoder', function() {//回调函数//实例化Geocodergeocoder = new AMap.Geocoder({city: "010" //城市,默认:“全国”});//TODO: 使用geocoder 对象完成相关功能var lnglatXY = [lang, lat]; //地图上所标点的坐标geocoder.getAddress(lnglatXY, function(status, result) {if (status === 'complete' && result.info === 'OK') {//获得了有效的地址信息:log('获取具体地理位置成功返回信息:' + result.regeocode.formattedAddress);if ($.isFunction(callback)) {callback(result.regeocode.formattedAddress);}} else {//获取地址失败log('获取具体地理位置失败返回信息:' + JSON.stringify(result));callback('');}});});}//如果5s后还未获取成功,则返回空if (n > 10) {window.clearInterval(t);t = null;log('获取具体地理位置失败返回信息:5s后都没有找到AMap.service');callback('');}}, 500);} else {common.Prompt(response.error);callback('');}});}//非法请求判断function illegalEntry() {//判断流程是否完整var _re = document.referrer || '';if (_re) {//当在QQ里时,document.referrer等于当前主机名,但是这两个值又不相等,不知道怎么解决//统一判断是否带有上下文_re = _re.indexOf('wxcpic') > -1 ? 1 : '';}var _c = window.location.href.indexOf('cpic.com.cn') > -1; //排除本地开发环境if (_re === '' && _c) {window.location.replace('../pages/share.html');}}var common = common || {};//设置本地缓存common.setLocalStorage = function(key, value, isJson) {if (window.localStorage) {if (isJson) {value = JSON.stringify(value);}window.localStorage[key] = value;} else {log("当前浏览器不支持localStorage");}};//获取本地缓存common.getLocalStorage = function(key, isJson) {if (window.localStorage) {var value = window.localStorage[key] || "";if (isJson && value) {value = JSON.parse(value);}return value;} else {log("当前浏览器不支持localStorage");}};//清除本地缓存common.removelocalStorage = function(key) {log("移除localStorage数据key=" + key);if (window.localStorage) {window.localStorage.removeItem(key);} else {log("当前浏览器不支持localStorage");}};//增加cookiecommon.addCookie = function(name, value, expiresHours) {var cookieString = name + "=" + escape(value);//判断是否设置过期时间if (expiresHours) {if (expiresHours > 0) {var date = new Date();date.setTime(date.getTime + expiresHours * 3600 * 1000);cookieString = cookieString + "; expires=" + date.toGMTString();}}document.cookie = cookieString;};//获取cookiecommon.getCookie = function(name) {var strCookie = document.cookie;var arrCookie = strCookie.split("; ");for (var i = 0; i < arrCookie.length; i++) {var arr = arrCookie[i].split("=");if (arr[0] == name) return arr[1];}return "";};//删除cookiecommon.deleteCookie = function(name) {var date = new Date();date.setTime(date.getTime() - 10000);document.cookie = name + "=v; expires=" + date.toGMTString();};//二秒后消失的弹出框common.Prompt = function(message) {if (!message) {message = '网络异常,请稍后重试...';}if ($('#e_ui_prompt').size() > 0) return;var _fontSize = $('body').css('font-size') || '36px';if (window.location.href.indexOf('smallChange.html') > -1) {_fontSize = '1.4rem';}//创建prompt框样式var type = "width:80%;padding:15px 0;border-radius:15px; color:#fff; background-color:#6c6c6c; text-align:center;font-size:" + _fontSize + "; opacity:0;position:fixed;top:75%;left:10%;z-index:100000;";//创建prompt框var h = $("<div style='" + type + "' id='e_ui_prompt'>" + message + "</div>");$('body').append(h);//改变透明度var i = 0;var t = window.setInterval(function() {i = i + 0.1;if (i >= 1) {window.clearInterval(t);t = null;i = 0;} else {$(h).css('opacity', i);}}, 80);//2秒后消失window.setTimeout(function() {var j = $(h).css('opacity');var ti = window.setInterval(function() {j = j - 0.1;if (j <= 0) {window.clearInterval(ti);ti = null;$(h).remove();} else {$(h).css('opacity', j);}}, 80);}, 2000);};//自适应移动设备common.adaptivePhone = function() {var content = '';var meta = document.createElement('meta');meta.name = "viewport";if (/Android (\d+\.\d+)/.test(navigator.userAgent)) {var version = parseFloat(RegExp.$1);if (version > 2.3) {var phoneScale = parseInt(window.screen.width) / 750;content = 'width=750, minimum-scale = ' + phoneScale + ', maximum-scale = ' + phoneScale + '';meta.onload = function(e) {log('viewport完成');};} else {content = 'width=750';}} else {content = 'width=750, user-scalable=no';}document.head.appendChild(meta);meta.setAttribute('content', content);};//是否为空common.isNull = function(value) {if (value) {return false;}return true;};//是否不为空common.isNotNull = function(value) {return !common.isNull(value);};function Map() {this.elements = new Array();//获取MAP元素个数this.size = function() {return this.elements.length;};//判断MAP是否为空this.isEmpty = function() {return (this.elements.length < 1);};//删除MAP所有元素this.clear = function() {this.elements = new Array();};//向MAP中增加元素(key, value)this.put = function(_key, _value) {this.elements.push({key: _key,value: _value});};//删除指定KEY的元素,成功返回True,失败返回Falsethis.remove = function(_key) {var bln = false;try {for (i = 0; i < this.elements.length; i++) {if (this.elements[i].key == _key) {this.elements.splice(i, 1);return true;}}} catch (e) {bln = false;}return bln;};//获取指定KEY的元素值VALUE,失败返回NULLthis.get = function(_key) {try {for (i = 0; i < this.elements.length; i++) {if (this.elements[i].key == _key) {return this.elements[i].value;}}} catch (e) {return null;}};//获取指定索引的元素(使用element.key,element.value获取KEY和VALUE),失败返回NULLthis.element = function(_index) {if (_index < 0 || _index >= this.elements.length) {return null;}return this.elements[_index];};//判断MAP中是否含有指定KEY的元素this.containsKey = function(_key) {varbln = false;try {for (i = 0; i < this.elements.length; i++) {if (this.elements[i].key == _key) {bln = true;}}} catch (e) {bln = false;}return bln;};//判断MAP中是否含有指定VALUE的元素this.containsValue = function(_value) {var bln = false;try {for (i = 0; i < this.elements.length; i++) {if (this.elements[i].value == _value) {bln = true;}}} catch (e) {bln = false;}return bln;};//获取MAP中所有VALUE的数组(ARRAY)this.values = function() {var arr = new Array();for (i = 0; i < this.elements.length; i++) {arr.push(this.elements[i].value);}return arr;};//获取MAP中所有KEY的数组(ARRAY)this.keys = function() {var arr = new Array();for (i = 0; i < this.elements.length; i++) {arr.push(this.elements[i].key);}return arr;};}//日志展示function _mobileLog() {if ($('#_mobileBtn').size() === 0) {var tlp = [];tlp.push('<div style="width:100%;height:100%;background:rgba(0,0,0,0.8);position:fixed;top:0;left:0;z-index:99999;">');tlp.push('<p style="width:100%;height:' + ($(window).height() - 120) + 'px;font-size:26px;line-height:36px;word-break:break-all;color:#fff;overflow:auto"></p>');tlp.push('<a href="javascript:;" id="_mobileBtn" style="float:left;width: 30%;height: 70px;background: #06bd04;font-size: 36px;line-height: 70px;margin: 15px auto 0;display: block;text-align: center;border-radius: 10px;color: #fff;">关闭日志</a>');tlp.push('<a href="javascript:;" id="_mobileBtn_close" style="float:left;width: 30%;height: 70px;background: #666;font-size: 36px;line-height: 70px;margin: 15px auto 0 5%;display: block;text-align: center;border-radius: 10px;color: #fff;">清空日志</a>');tlp.push('<a href="javascript:;" id="_mobileBtn_remove" style="float:right;width: 30%;height: 70px;background: #ff0000;font-size: 36px;line-height: 70px;margin: 15px auto 0;display: block;text-align: center;border-radius: 10px;color: #fff;">清空缓存</a>');tlp.push('</div>');$('body').append(tlp.join(''));$('#_mobileBtn').prev('p').html(sessionStorage._mobile_log || '无');//关闭事件$('#_mobileBtn').on('click', function() {$(this).parent().remove();});//清空日志$('#_mobileBtn_close').on('click', function() {sessionStorage._mobile_log = '';$('#_mobileBtn').prev('p').html('');$('#_mobileBtn').parent().remove();});//清除缓存$('#_mobileBtn_remove').on('click', function() {alert('将清空本地全部缓存');window.localStorage.clear();window.sessionStorage.clear();});}}//获取页面错误消息/** * @param {String} errorMessage  错误信息 * @param {String} scriptURI   出错的文件 * @param {Long}  lineNumber   出错代码的行号 * @param {Long}  columnNumber  出错代码的列号 * @param {Object} errorObj    错误的详细信息,Anything */window.onerror = function(errorMessage, scriptURI, lineNumber, columnNumber, errorObj) {log("<strong style='color:red'>****************************************</strong>");log("错误信息:" + errorMessage);log("出错文件:" + scriptURI);log("出错行号:" + lineNumber);log("出错列号:" + columnNumber);log("错误详情:" + errorObj);log("<strong style='color:red'>****************************************</strong>");};//根据不同环境显示日志按钮function _showLog() {var showFlag = isShowOrNot();if (showFlag) {$('body').append('<div id="_mobile_log_mark" style="width:90px;height:60px;border:1px solid #ddd;border-radius: 0 20px 20px 0;background:rgba(0,0,0,0.2);line-height:60px;font-size:30px;color:#fff;text-align:center;font-weight:600;position:fixed;bottom:0;left:0;z-index:99996;">LOG</div>');//打开事件$('#_mobile_log_mark').on('click', function(event) {_mobileLog();});}}//特定条件显示log和function isShowOrNot() {var _openIDs = ['oAl3ejopthT-F_gXaXtiWeWlSYtA', 'oAl3ejnALwJL0tkgO8hC2I8ib3_c', 'oAl3ejsuElGxqZ_fOboKER8R76AI', 'oAl3ejpyMhGB8ZgkkRgS-URfc3qg', 'oAl3ejhtSwxyKJ5pH2KrZ5IO_Q9s', 'oAl3ejtfoUAogv0T_vN8GKVaovUw', 'oAl3ejv6_P15A4kt-w18d-HP0lm4', 'oAl3ejtfQ25eZYRI2xPd9Mn_u6eo','oAl3ejksiZ0XknBgKp33e0p0RtwM','oAl3ejsn1DI6YVpvbdikniDyF9vk'];var _openid = getHash('openid') || '';if (_openid) {sessionStorage._exist_log = _openid;} else {_openid = sessionStorage._exist_log;}var _exist = $.inArray(_openid, _openIDs) > -1;var _host = window.location.hostname;if (_host.indexOf("ftsurvey") > -1 || (_host.indexOf('surveysit') > -1 && _exist)) {return true;}return false;}//配置是否启用开关function builtSwitck() {/* * 配置开关选项类 * */this.optionSwitch = {};/* * 本地数据开关 * true 时 用户的ajax请求使用的是本地的模拟数据 * * */var locData = false;/* * ajax请求默认方法(用于开关的转换) * */var ajaxrequestfn = null;Object.defineProperty(this.optionSwitch, 'locData', {set: function(a) {//ajax没有加载好时,等待。var ajax = window.ajax || 0;if (!ajax) {var lazytime = setTimeout(function() {clearTimeout(lazytime);this.optionSwitch.locData = a;}, 1500);return;}if (typeof a !== "boolean") return;locData = a;ajaxrequestfn = ajax.request;if (a) {log('本地数据开关开启');//获取ajax修改默认方法ajax.request = function(param, callback) {//准备加载本地数据loadScript('../components/utils/localData.js', function(response) {if (response.status) {window.setTimeout(function() {if (window.localdataobj) {localdataobj.paselocaldata(param, function(data) {if (data.status) {var backdata = data.responseBody;//返回数据callback({status: '000000',responseBody: backdata});} else {//打印错误信息,执行默认ajax方法log(data.message);ajaxrequestfn.call(ajax, param, callback);}});}}, 2000);}});};} else {log('本地数据开关关闭');//如果没有执行过set value=true方法不做处理if (!locData) return;//重新恢复ajax请求ajax.request = function(param, callback) {ajaxrequestfn.call(ajax, param, callback);};}},get: function() {return locData;}});}//自定义执行函数$(function() {//显示日志_showLog();//点击事件监听utils.loadScript('../components/libs/jqlog.js', function(response) {});});var Switck = new builtSwitck();utils = {log: log,isUndefined: isUndefined,isArray: isArray,isObject: isObject,isString: isString,isBoolean: isBoolean,isBlank: isBlank,redirection: redirection,server: server,common: common,getHash: getHash,map: Map,loadStyle: loadStyle,loadScript: loadScript,getAddress: getAddress,webLogs: webLogs,illegalEntry: illegalEntry,optionSwitch: Switck.optionSwitch,mobileLog: _mobileLog,getPageName: getPageName,showTakeVideo: isShowOrNot};}(window.Zepto, utils);

0 0