haoutil-src.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  1. /**
  2. * JS常用静态方法类库
  3. * 源码地址:https://github.com/muyao1987/haoutil
  4. * 版本信息:v2.5.4
  5. * 编译日期:2021-10-22 19:40:50
  6. * 版权所有:Copyright by 火星科技 木遥 http://marsgis.cn
  7. */
  8. var haoutil = haoutil || {};
  9. if(typeof exports === 'object'){
  10. exports.haoutil = haoutil
  11. }
  12. else{
  13. window.haoutil = haoutil
  14. }
  15. haoutil.version = "2.5.4";
  16. haoutil.name = "木遥 通用常用JS方法类库";
  17. haoutil.author = "木遥 , 微信: http://marsgis.cn/weixin.html";
  18. haoutil.update = "2021-10-19";
  19. haoutil.website ='https://github.com/muyao1987/haoutil'
  20. haoutil.msg = function (msg) {
  21. if(haoutil.isutil.isNull(msg)){
  22. msg = "未知";
  23. }
  24. else{
  25. if(typeof msg == 'object'){
  26. msg = JSON.stringify(msg);
  27. }
  28. }
  29. if (window.toastr)//此方法需要引用toastr
  30. toastr.info(msg);
  31. else if (window.layer)
  32. layer.msg(msg);//此方法需要引用layer.js
  33. else
  34. alert(msg);
  35. };
  36. haoutil.tip = haoutil.msg;
  37. haoutil.oneMsg = function (msg, key) {
  38. if (!haoutil.storage.get(key)) {
  39. haoutil.msg(msg);
  40. haoutil.storage.add(key, true);
  41. }
  42. }
  43. haoutil.alert = function (msg, title) {
  44. if(haoutil.isutil.isNull(msg)){
  45. msg = "未知";
  46. }
  47. else{
  48. if(typeof msg == 'object'){
  49. msg = JSON.stringify(msg);
  50. }
  51. }
  52. if (window.layer)//此方法需要引用layer.js
  53. layer.alert(msg, {
  54. title: title || '提示',
  55. skin: 'layui-layer-lan layer-mars-dialog',
  56. closeBtn: 0,
  57. anim: 0
  58. });
  59. else
  60. alert(msg);
  61. };
  62. haoutil.loading = {
  63. index: -1,
  64. show: function (param) {
  65. this.close();
  66. if (window.NProgress) {//此方法需要引用NProgress
  67. param = param || {};
  68. if (param.color) {
  69. param.template = '<div class="bar ' + (param.className || '') + '" style="background-color:' + param.color + ';" role="bar"></div><div class="spinner" role="spinner"><div class="spinner-icon"></div></div>';
  70. }
  71. else {
  72. param.template = '<div class="bar ' + (param.className || '') + '" role="bar"></div><div class="spinner" role="spinner"><div class="spinner-icon"></div></div>';
  73. }
  74. NProgress.configure(param);
  75. NProgress.start();
  76. }
  77. else if (window.layer) {//此方法需要引用layer.js
  78. this.index = layer.load(2, { shade: [0.3, '#000000'] });
  79. }
  80. },
  81. hide: function () {
  82. this.close();
  83. },
  84. close: function () {
  85. if (window.NProgress) {
  86. NProgress.done(true);
  87. }
  88. else if (window.layer) {
  89. if (this.index != -1)
  90. layer.close(this.index);
  91. this.index = -1;
  92. }
  93. }
  94. };
  95. //js原生对象扩展
  96. // //标识是否扩展数组对象
  97. // if (!window.noArrayPrototype) {
  98. // //扩展array数组方法,不要用for(var i in arr)来循环数组
  99. // // Array.prototype.indexOf = Array.prototype.indexOf || function (val) {
  100. // // for (var i = 0; i < this.length; i++) {
  101. // // if (this[i] == val) return i;
  102. // // }
  103. // // return -1;
  104. // // };
  105. // // Array.prototype.remove = Array.prototype.remove || function (val) {
  106. // // for (var i = 0; i < this.length; i++) {
  107. // // if (this[i] == val) {
  108. // // this.splice(i, 1);
  109. // // break;
  110. // // }
  111. // // }
  112. // // };
  113. // // Array.prototype.insert = Array.prototype.insert || function (item, index) {
  114. // // if (index == null) index = 0;
  115. // // this.splice(index, 0, item);
  116. // // };
  117. // }
  118. String.prototype.startsWith = String.prototype.startsWith || function (str) {
  119. return this.slice(0, str.length) == str;
  120. };
  121. //判断当前字符串是否以str结束
  122. String.prototype.endsWith = String.prototype.endsWith || function (str) {
  123. return this.slice(-str.length) == str;
  124. };
  125. String.prototype.replaceAll = String.prototype.replaceAll || function (oldstring, newstring) {
  126. return this.replace(new RegExp(oldstring, "gm"), newstring);
  127. }
  128. /**
  129. * 对Date的扩展,将 Date 转化为指定格式的String
  130. * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q) 可以用 1-2 个占位符
  131. * 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
  132. *
  133. * (new Date()).format("yyyy-MM-dd HH:mm:ss") ==> 2017-01-09 08:35:26
  134. * (new Date()).format("yyyy-M-d HH:mm:ss") ==> 2017-1-9 08:35:26
  135. * (new Date()).format("yyyy-M-d h:m:s.S") ==> 2016-7-2 8:9:4.18
  136. * (new Date()).format("yyyy-MM-dd hh:mm:ss.S") ==> 2016-07-02 08:09:04.423
  137. * (new Date()).format("yyyy-MM-dd E HH:mm:ss") ==> 2016-03-10 二 20:09:04
  138. * (new Date()).format("yyyy-MM-dd EE hh:mm:ss") ==> 2016-03-10 周二 08:09:04
  139. * (new Date()).format("yyyy-MM-dd EEE hh:mm:ss") ==> 2016-03-10 星期二 08:09:04
  140. */
  141. Date.prototype.format = function (fmt) {
  142. var o = {
  143. "M+": this.getMonth() + 1, //月份
  144. "d+": this.getDate(), //日
  145. "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时
  146. "H+": this.getHours(), //小时
  147. "m+": this.getMinutes(), //分
  148. "s+": this.getSeconds(), //秒
  149. "q+": Math.floor((this.getMonth() + 3) / 3), //季度
  150. "S": this.getMilliseconds() //毫秒
  151. };
  152. var week = {
  153. "0": "\u65e5",
  154. "1": "\u4e00",
  155. "2": "\u4e8c",
  156. "3": "\u4e09",
  157. "4": "\u56db",
  158. "5": "\u4e94",
  159. "6": "\u516d"
  160. };
  161. if (/(y+)/.test(fmt)) {
  162. fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  163. }
  164. if (/(E+)/.test(fmt)) {
  165. fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "\u661f\u671f" : "\u5468") : "") + week[this.getDay() + ""]);
  166. }
  167. for (var k in o) {
  168. if (new RegExp("(" + k + ")").test(fmt)) {
  169. fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  170. }
  171. }
  172. return fmt;
  173. };
  174. /* 2017-10-27 08:39:39 | 修改 木遥(微信: http://marsgis.cn/weixin.html) */
  175. haoutil.array = (function () {
  176. //============内部私有属性及方法============
  177. function indexOf(arr,val) {
  178. for (var i = 0; i < arr.length; i++) {
  179. if (arr[i] == val) return i;
  180. }
  181. return -1;
  182. }
  183. function remove(arr,val) {
  184. for (var i = 0; i < arr.length; i++) {
  185. if (arr[i] == val) {
  186. arr.splice(i, 1);
  187. break;
  188. }
  189. }
  190. }
  191. function insert(arr,item, index) {
  192. if (index == null) index = 0;
  193. arr.splice(index, 0, item);
  194. }
  195. //===========对外公开的属性及方法=========
  196. return {
  197. indexOf: indexOf,
  198. remove: remove,
  199. insert: insert,
  200. };
  201. })();
  202. /* 2017-12-8 09:39:39 | 修改 木遥(微信: http://marsgis.cn/weixin.html) */
  203. haoutil.color = (function () {
  204. // "颜色 相关操作类";
  205. //============内部私有属性及方法============
  206. //随机颜色
  207. function random() {
  208. return '#' +
  209. (function (color) {
  210. return (color += '0123456789abcdef'[Math.floor(Math.random() * 16)]) && (color.length == 6) ? color : arguments.callee(color);
  211. })('');
  212. }
  213. //===========对外公开的属性及方法=========
  214. return {
  215. random: random
  216. };
  217. })();
  218. /* 2017-10-10 13:32:56 | 修改 木遥(微信: http://marsgis.cn/weixin.html) */
  219. haoutil.cookie = (function () {
  220. //"cookie 相关操作类";
  221. //============内部私有属性及方法============
  222. var _isH5Mobile;
  223. function isH5Mobile(value) {
  224. _isH5Mobile = value;
  225. }
  226. //添加cookie
  227. function add(name, value, days) {
  228. //判断是否设置过期时间,0代表关闭浏览器时失效
  229. var date;
  230. if (days > 0) {
  231. date = new Date();
  232. date.setTime(date.getTime + days * 24 * 60 * 60 * 1000); //单位是天后失效
  233. }
  234. else {
  235. date = new Date(0x7fffffff * 1e3);
  236. }
  237. var cookieString = name + "=" + escape(value) + "; expires=" + date.toGMTString();
  238. if (_isH5Mobile && window['plus'] != null) {
  239. plus.navigator.setCookie(name, cookieString);
  240. } else {
  241. document.cookie = cookieString;
  242. }
  243. }
  244. //获取cookie
  245. function get(name) {
  246. var strCookie
  247. if (_isH5Mobile && window['plus'] != null) {
  248. strCookie = plus.navigator.getCookie(name);
  249. if (strCookie == null) return null;
  250. } else {
  251. strCookie = document.cookie;
  252. }
  253. var arrCookie = strCookie.split("; ");
  254. for (var i = 0; i < arrCookie.length; i++) {
  255. var arr = arrCookie[i].split("=");
  256. if (arr[0] == name) {
  257. return unescape(arr[1]);
  258. }
  259. }
  260. return null;
  261. }
  262. //删除cookie
  263. function del(name) {
  264. if (_isH5Mobile && window['plus'] != null) {
  265. plus.navigator.removeCookie(name);
  266. }
  267. else {
  268. var date = new Date();
  269. date.setTime(date.getTime() - 10000); //设定一个过去的时间即可
  270. document.cookie = name + "=v; expires=" + date.toGMTString();
  271. }
  272. }
  273. //===========对外公开的属性及方法=========
  274. return {
  275. isH5Mobile: isH5Mobile,
  276. add: add,
  277. get: get,
  278. del: del
  279. };
  280. })();
  281. /* 2017-8-31 17:26:30 | 修改 木遥(微信: http://marsgis.cn/weixin.html) */
  282. haoutil.file = (function () {
  283. //"文件 相关操作类";
  284. //============内部私有属性及方法============
  285. function _download(fileName, blob) {
  286. var aLink = document.createElement('a');
  287. aLink.download = fileName;
  288. aLink.href = URL.createObjectURL(blob);
  289. document.body.appendChild(aLink);
  290. aLink.click();
  291. document.body.removeChild(aLink);
  292. }
  293. //下载保存文件
  294. function downloadFile(fileName, string) {
  295. var blob = new Blob([string]);
  296. _download(fileName, blob);
  297. }
  298. //下载导出图片
  299. function downloadImage(name, canvas) {
  300. var base64 = canvas.toDataURL("image/png");
  301. var blob = base64Img2Blob(base64);
  302. _download(name + '.png', blob);
  303. }
  304. //下载导出图片
  305. function downloadBase64Image(name, base64) {
  306. var blob = base64Img2Blob(base64);
  307. _download(name + '.png', blob);
  308. }
  309. function base64Img2Blob(code) {
  310. var parts = code.split(';base64,');
  311. var contentType = parts[0].split(':')[1];
  312. var raw = window.atob(parts[1]);
  313. var rawLength = raw.length;
  314. var uInt8Array = new Uint8Array(rawLength);
  315. for (var i = 0; i < rawLength; ++i) {
  316. uInt8Array[i] = raw.charCodeAt(i);
  317. }
  318. return new Blob([uInt8Array], { type: contentType });
  319. }
  320. //===========对外公开的属性及方法=========
  321. return {
  322. download: _download,
  323. downloadFile: downloadFile,
  324. downloadImage: downloadImage,
  325. downloadBase64Image: downloadBase64Image,
  326. base64Img2Blob: base64Img2Blob
  327. };
  328. })();
  329. /* 2017-12-5 13:38:32 | 修改 木遥(微信: http://marsgis.cn/weixin.html) */
  330. haoutil.isutil = (function () {
  331. // "判断 相关操作类";
  332. //============内部私有属性及方法============
  333. function isArray(obj) {
  334. if (typeof Array.isArray === "function") {
  335. return Array.isArray(obj);
  336. } else {
  337. return Object.prototype.toString.call(obj) === "[object Array]";
  338. }
  339. }
  340. function isString(str) {
  341. return (typeof str == 'string') && str.constructor == String;
  342. }
  343. function isNumber(obj) {
  344. return (typeof obj == 'number') && obj.constructor == Number;
  345. }
  346. function isDate(obj) {
  347. return (typeof obj == 'object') && obj.constructor == Date;
  348. }
  349. function isFunction(obj) {
  350. return (typeof obj == 'function') && obj.constructor == Function;
  351. }
  352. function isObject(obj) {
  353. return Object.prototype.toString.call(obj) === "[object Object]";
  354. }
  355. function isNull(value) {
  356. if (value == null) return true;
  357. if (isString(value) && value == "") return true;
  358. if (isNumber(value) && isNaN(value)) return true;
  359. return false;
  360. }
  361. function isNotNull(value) {
  362. return !isNull(value);
  363. }
  364. //===========对外公开的属性及方法=========
  365. return {
  366. isNull: isNull,
  367. isNotNull: isNotNull,
  368. isArray: isArray,
  369. isString: isString,
  370. isNumber: isNumber,
  371. isDate: isDate,
  372. isFunction: isFunction,
  373. isObject: isObject
  374. };
  375. })();
  376. /* 2017-8-10 13:50:49 | 修改 木遥(微信: http://marsgis.cn/weixin.html) */
  377. haoutil.math = (function () {
  378. // "数学 相关操作类";
  379. //============内部私有属性及方法============
  380. function random(min, max) {
  381. return Math.floor(Math.random() * (max - min + 1) + min);
  382. }
  383. //随机数组中随机取1个元素
  384. function getArrayRandomOne(arr) {
  385. var n = random(0, arr.length - 1);
  386. return arr[n];
  387. }
  388. //补零padLeft0
  389. function padLeft0(numStr, len) {
  390. numStr = String(numStr);
  391. var len = numStr.length;
  392. while (len < n) {
  393. numStr = "0" + numStr;
  394. len++;
  395. }
  396. return numStr;
  397. }
  398. //===========对外公开的属性及方法=========
  399. return {
  400. getArrayRandomOne: getArrayRandomOne,
  401. random: random,
  402. padLeft0: padLeft0
  403. };
  404. })();
  405. haoutil.storage = (function () {
  406. //"localStorage 相关操作类";
  407. var _storage;
  408. //添加
  409. function add(name, data) {
  410. _storage = window.localStorage;
  411. if (_storage == null) return;
  412. _storage.setItem(name, data);
  413. }
  414. //获取cookie
  415. function get(name) {
  416. _storage = window.localStorage;
  417. if (_storage == null) return;
  418. var data = _storage.getItem(name);
  419. return data;
  420. }
  421. function del(name) {
  422. _storage = window.localStorage;
  423. if (_storage == null) return;
  424. _storage.removeItem(name);
  425. }
  426. //===========对外公开的属性及方法=========
  427. return {
  428. add: add,
  429. get: get,
  430. del: del
  431. };
  432. })();
  433. /* 2017-10-27 08:39:39 | 修改 木遥(微信: http://marsgis.cn/weixin.html) */
  434. haoutil.str = (function () {
  435. // "字符串 相关操作类";
  436. //============内部私有属性及方法============
  437. //判断字符是否是中文字符
  438. function isChinese(s) {
  439. var patrn = /[\u4E00-\u9FA5]|[\uFE30-\uFFA0]/gi;
  440. if (!patrn.exec(s)) {
  441. return false;
  442. } else {
  443. return true;
  444. }
  445. }
  446. /** 单位换算,格式化显示长度 */
  447. function formatLength(val, unit) {
  448. if (val == null) return "";
  449. val = Number(val);
  450. if (unit == null || unit == "auto") {
  451. if (val < 1000)
  452. unit = "m";
  453. else
  454. unit = "km";
  455. }
  456. var valstr = "";
  457. switch (unit) {
  458. default:
  459. case "m":
  460. valstr = val.toFixed(2) + '米';
  461. break;
  462. case "km":
  463. valstr = (val * 0.001).toFixed(2) + '公里';
  464. break;
  465. case "mile":
  466. valstr = (val * 0.00054).toFixed(2) + '海里';
  467. break;
  468. case "zhang":
  469. valstr = (val * 0.3).toFixed(2) + '丈';
  470. break;
  471. }
  472. return valstr;
  473. }
  474. /** 进行单位换算,格式化显示面积 */
  475. function formatArea(val, unit) {
  476. if (val == null) return "";
  477. val = Number(val);
  478. if (unit == null || unit == "auto") {
  479. if (val < 1000000)
  480. unit = "m";
  481. else
  482. unit = "km";
  483. }
  484. var valstr = "";
  485. switch (unit) {
  486. default:
  487. case "m":
  488. valstr = val.toFixed(2) + '平方米';
  489. break;
  490. case "km":
  491. valstr = (val / 1000000).toFixed(2) + '平方公里';
  492. break;
  493. case "mu":
  494. valstr = (val * 0.0015).toFixed(2) + '亩';
  495. break;
  496. case "ha":
  497. valstr = (val * 0.0001).toFixed(2) + '公顷';
  498. break;
  499. }
  500. return valstr;
  501. }
  502. //格式化时间
  503. function formatTime(strtime) {
  504. strtime = Number(strtime)||0;
  505. if (strtime < 60)
  506. return strtime.toFixed(0) + "秒";
  507. else if (strtime >= 60 && strtime < 3600) {
  508. var miao = Math.floor(strtime % 60);
  509. return Math.floor(strtime / 60) + "分钟" + (miao != 0 ? (miao + "秒") : "");
  510. }
  511. else {
  512. strtime = Math.floor(strtime / 60); //秒转分钟
  513. return Math.floor(strtime / 60) + "小时" + Math.floor(strtime % 60) + "分钟";
  514. }
  515. }
  516. var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""); //索引表
  517. /**
  518.    * @description 将二进制序列转换为Base64编码
  519.    * @param {String}
  520.    * @return {String}
  521.    */
  522. function binToBase64(bitString) {
  523. var result = "";
  524. var tail = bitString.length % 6;
  525. var bitStringTemp1 = bitString.substr(0, bitString.length - tail);
  526. var bitStringTemp2 = bitString.substr(bitString.length - tail, tail);
  527. for (var i = 0; i < bitStringTemp1.length; i += 6) {
  528. var index = parseInt(bitStringTemp1.substr(i, 6), 2);
  529. result += code[index];
  530. }
  531. bitStringTemp2 += new Array(7 - tail).join("0");
  532. if (tail) {
  533. result += code[parseInt(bitStringTemp2, 2)];
  534. result += new Array((6 - tail) / 2 + 1).join("=");
  535. }
  536. return result;
  537. }
  538. /**
  539.    * @description 将base64编码转换为二进制序列
  540.    * @param {String}
  541.    * @return {String}
  542.    */
  543. function base64ToBin(str) {
  544. var bitString = "";
  545. var tail = 0;
  546. for (var i = 0; i < str.length; i++) {
  547. if (str[i] != "=") {
  548. var decode = code.indexOf(str[i]).toString(2);
  549. bitString += (new Array(7 - decode.length)).join("0") + decode;
  550. } else {
  551. tail++;
  552. }
  553. }
  554. return bitString.substr(0, bitString.length - tail * 2);
  555. }
  556. /**
  557.    * @description 将字符转换为二进制序列
  558.    * @param {String} str
  559.    * @return {String} 
  560.    */
  561. function stringToBin(str) {
  562. var result = "";
  563. for (var i = 0; i < str.length; i++) {
  564. var charCode = str.charCodeAt(i).toString(2);
  565. result += (new Array(9 - charCode.length).join("0") + charCode);
  566. }
  567. return result;
  568. }
  569. /**
  570.    * @description 将二进制序列转换为字符串
  571.    * @param {String} Bin
  572.    */
  573. function BinToStr(Bin) {
  574. var result = "";
  575. for (var i = 0; i < Bin.length; i += 8) {
  576. result += String.fromCharCode(parseInt(Bin.substr(i, 8), 2));
  577. }
  578. return result;
  579. }
  580. function base64(str) {
  581. return binToBase64(stringToBin(str));
  582. }
  583. function decodeBase64(str) {
  584. return BinToStr(base64ToBin(str));
  585. }
  586. //===========对外公开的属性及方法=========
  587. return {
  588. isChinese: isChinese,
  589. formatLength: formatLength,
  590. formatArea: formatArea,
  591. formatTime: formatTime,
  592. base64: base64,
  593. decodeBase64: decodeBase64
  594. };
  595. })();
  596. /* 2017-10-27 08:31:05 | 修改 木遥(微信: http://marsgis.cn/weixin.html) */
  597. haoutil.system = (function () {
  598. // 系统级 或 浏览器 相关操作类";
  599. //============内部私有属性及方法============
  600. //url参数获取
  601. function getRequest(target) {
  602. var theRequest = new Object();
  603. try {//屏蔽跨域时报错
  604. target = target || window;
  605. var url = target.location.search; //获取url中"?"符后的字串
  606. if (url.indexOf("?") != -1) {
  607. var str = url.substr(1);
  608. var strs = str.split("&");
  609. for (var i = 0; i < strs.length; i++) {
  610. theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
  611. }
  612. }
  613. } catch (e) { }
  614. return theRequest;
  615. }
  616. function getRequestByName(name, defval, target) {
  617. try {
  618. target = target || window;
  619. var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  620. var r = target.location.search.substr(1).match(reg);
  621. if (r != null) return decodeURI(r[2]);
  622. } catch (e) { }
  623. return defval;
  624. }
  625. function getWindowSize() {
  626. if (typeof window.innerWidth != 'undefined') {
  627. return {
  628. width: window.innerWidth,
  629. height: window.innerHeight
  630. }
  631. } else {
  632. return {
  633. width: document.documentElement.clientWidth,
  634. height: document.documentElement.clientHeight
  635. }
  636. }
  637. }
  638. //获取浏览器类型及版本
  639. function getExplorerInfo() {
  640. var explorer = window.navigator.userAgent.toLowerCase();
  641. //ie
  642. if (explorer.indexOf("msie") >= 0) {
  643. var ver = Number(explorer.match(/msie ([\d]+)/)[1]);
  644. return { type: "IE", version: ver };
  645. }
  646. //firefox
  647. else if (explorer.indexOf("firefox") >= 0) {
  648. var ver = Number(explorer.match(/firefox\/([\d]+)/)[1]);
  649. return { type: "Firefox", version: ver };
  650. }
  651. //Chrome
  652. else if (explorer.indexOf("chrome") >= 0) {
  653. var ver = Number(explorer.match(/chrome\/([\d]+)/)[1]);
  654. return { type: "Chrome", version: ver };
  655. }
  656. //Opera
  657. else if (explorer.indexOf("opera") >= 0) {
  658. var ver = Number(explorer.match(/opera.([\d]+)/)[1]);
  659. return { type: "Opera", version: ver };
  660. }
  661. //Safari
  662. else if (explorer.indexOf("Safari") >= 0) {
  663. var ver = Number(explorer.match(/version\/([\d]+)/)[1]);
  664. return { type: "Safari", version: ver };
  665. }
  666. return { type: explorer, version: -1 };
  667. }
  668. //浏览器
  669. function isPCBroswer() {
  670. var sUserAgent = navigator.userAgent.toLowerCase();
  671. var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
  672. var bIsIphoneOs = sUserAgent.match(/iphone/i) == "iphone";
  673. var bIsMidp = sUserAgent.match(/midp/i) == "midp";
  674. var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
  675. var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
  676. var bIsAndroid = sUserAgent.match(/android/i) == "android";
  677. var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
  678. var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
  679. if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {
  680. return false;
  681. } else {
  682. return true;
  683. }
  684. }
  685. function clone(obj, removeKeys, level) {
  686. if (level == null) level = 9; //避免死循环,拷贝的层级最大深度
  687. if (removeKeys == null) removeKeys = ["_layer"];
  688. if (null == obj || "object" != typeof obj) return obj;
  689. // Handle Date
  690. if (haoutil.isutil.isDate(obj)) {
  691. var copy = new Date();
  692. copy.setTime(obj.getTime());
  693. return copy;
  694. }
  695. // Handle Array
  696. if (haoutil.isutil.isArray(obj) && level >= 0) {
  697. var copy = [];
  698. for (var i = 0, len = obj.length; i < len; ++i) {
  699. copy[i] = clone(obj[i], removeKeys, level - 1);
  700. }
  701. return copy;
  702. }
  703. // Handle Object
  704. if (typeof obj === 'object' && level >= 0) {
  705. try {
  706. var copy = {};
  707. for (var attr in obj) {
  708. if (typeof attr === 'function') continue;
  709. if (removeKeys.indexOf(attr) != -1) continue;
  710. if (obj.hasOwnProperty(attr))
  711. copy[attr] = clone(obj[attr], removeKeys, level - 1);
  712. }
  713. return copy;
  714. }
  715. catch (e) { console.log(e); }
  716. }
  717. return obj;
  718. }
  719. function jsonp(url, data, callback) {
  720. var jsonp = function (url, data, callback) {
  721. var fnSuffix = Math.random().toString().replace('.', '');
  722. var cbFuncName = 'my_json_cb_' + fnSuffix;
  723. // 不推荐
  724. window[cbFuncName] = callback;
  725. var querystring = url.indexOf('?') == -1 ? '?' : '&';
  726. for (var key in data) {
  727. querystring += key + '=' + data[key] + '&';
  728. }
  729. querystring += 'callback=' + cbFuncName;
  730. var scriptElement = document.createElement('script');
  731. scriptElement.src = url + querystring;
  732. document.body.appendChild(scriptElement);
  733. };
  734. window.$jsonp = jsonp;
  735. }
  736. //公共方法
  737. function getHtml(url, callback) {
  738. $.ajax({
  739. url: url,
  740. type: "GET",
  741. dataType: 'html',
  742. timeout: 0, //永不超时
  743. success: function (data) {
  744. callback(data);
  745. }
  746. });
  747. }
  748. var nHead = document.head || document.getElementsByTagName('head')[0];
  749. // loadCss 用于载入css资源
  750. function loadCss(url, async) {
  751. var node = document.createElement('link');
  752. node.rel = 'stylesheet';
  753. node.async = async;
  754. node.href = url;
  755. nHead.appendChild(node);
  756. }
  757. // loadJs 用于载入js资源
  758. function loadJs(url, async) {
  759. var node = document.createElement('script');
  760. node.charset = 'utf-8';
  761. node.async = async;
  762. node.src = url;
  763. nHead.appendChild(node);
  764. }
  765. var cssExpr = new RegExp('\\.css');
  766. function loadResource(url, async) {
  767. if (cssExpr.test(url)) {
  768. loadCss(url, async);
  769. } else {
  770. loadJs(url, async);
  771. }
  772. }
  773. //===========对外公开的属性及方法=========
  774. return {
  775. getRequest: getRequest,
  776. getRequestByName: getRequestByName,
  777. getExplorerInfo: getExplorerInfo,
  778. isPCBroswer: isPCBroswer,
  779. clone: clone,
  780. jsonp: jsonp,
  781. getWindowSize: getWindowSize,
  782. getHtml: getHtml,
  783. loadCss: loadCss,
  784. loadJs: loadJs,
  785. loadResource: loadResource
  786. };
  787. })();