博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JavaScript项目中封装的util常用工具
阅读量:4085 次
发布时间:2019-05-25

本文共 16549 字,大约阅读时间需要 55 分钟。

/** * * @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 + '
'; webLogs(_tit); console && console.log && console.log(_tit); } //判断是否为undefined function 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 + '/ch5'; } //文件是否存在 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)) { //webkit if (node.sheet) { isLoaded = true; } } else if (node.sheet) { // for Firefox try { if (node.sheet.cssRules) { isLoaded = true; } } catch (ex) { // NS_ERROR_DOM_SECURITY_ERR if (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() { //回调函数 //实例化Geocoder geocoder = 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('wxic') > -1 ? 1 : ''; } var _c = window.location.href.indexOf('cp.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"); } }; //增加cookie common.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; }; //获取cookie common.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 ""; }; //删除cookie common.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 = $("
" + message + "
"); $('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,失败返回False this.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,失败返回NULL this.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),失败返回NULL this.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('
'); tlp.push('

'); tlp.push('
关闭日志'); tlp.push('
清空日志'); tlp.push('
清空缓存'); tlp.push('
'); $('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("****************************************"); log("错误信息:" + errorMessage); log("出错文件:" + scriptURI); log("出错行号:" + lineNumber); log("出错列号:" + columnNumber); log("错误详情:" + errorObj); log("****************************************"); }; //根据不同环境显示日志按钮 function _showLog() { var showFlag = isShowOrNot(); if (showFlag) { $('body').append('
LOG
'); //打开事件 $('#_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);

转载地址:http://yhhni.baihongyu.com/

你可能感兴趣的文章
浅谈JavaScript--声明提升
查看>>
Charles网络抓包工具使用教程
查看>>
React 组件模式-有状态组件 x 无状态组件、容器组件 x 展示组件、高阶组件 x 渲染回调(函数作为子组件)
查看>>
Vue2.0 Vuex初始化及歌手数据的配置
查看>>
Flutter 中 ListView 组件的子元素曝光统计
查看>>
H5唤起APP指南(附开源唤端库)
查看>>
使用顶级 VSCode 扩展来加快开发 JavaScript
查看>>
webpack4.0各个击破(1)—— html部分
查看>>
webpack4.0各个击破(2)—— CSS篇
查看>>
react native 滑动价格区间(step 支持一格移动大小)
查看>>
React Native下拉图片放大动画
查看>>
使用webpack4打造自己的前端工作流
查看>>
小程序开发技巧总结
查看>>
Vue.js 代码优化浅谈
查看>>
Flutter布局
查看>>
Flutter知识点: Route & Navigator
查看>>
flutter之从零开始搭建(一)之 BottomNavigationBar
查看>>
Flutter 中 ListView 的使用
查看>>
App整体布局框架搭建
查看>>
VueRouter完全指北
查看>>