util.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. // 引用 https://web.tianyunperfect.cn/simple/js/util.js
  2. function lt(obj) {
  3. console.table(JSON.parse(JSON.stringify(obj)));
  4. }
  5. /**
  6. * 深度克隆
  7. * @param obj
  8. * @returns {any}
  9. */
  10. function deepClone(obj) {
  11. return JSON.parse(JSON.stringify(obj))
  12. }
  13. // 日期工具类
  14. const dataUtil = {
  15. // 日期 -> 字符串:formatDate(date, 'yyyy-MM-dd hh:mm:ss');
  16. formatDate: function (date, format) {
  17. const pad = (n) => (n < 10 ? '0' + n : n);
  18. const replacements = {
  19. 'yyyy': date.getFullYear(),
  20. 'MM': pad(date.getMonth() + 1),
  21. 'dd': pad(date.getDate()),
  22. 'hh': pad(date.getHours()),
  23. 'mm': pad(date.getMinutes()),
  24. 'ss': pad(date.getSeconds()),
  25. 'qq': Math.floor((date.getMonth() + 3) / 3), //季度
  26. 'SSS': pad(date.getMilliseconds(), 3) //毫秒
  27. };
  28. let result = format;
  29. for (const key in replacements) {
  30. result = result.replace(key, replacements[key]);
  31. }
  32. return result;
  33. },
  34. // 日期字符串 -> 日期: parseDate("2022-10-30 16:13:49")
  35. parseDate: function (dateString) {
  36. const date = new Date(Date.parse(dateString));
  37. return date;
  38. },
  39. // 当前日期
  40. getNowStr: function () {
  41. return this.formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss');
  42. },
  43. }
  44. // 添加响应拦截器
  45. axios.interceptors.response.use(function (response) {
  46. // 对响应数据做点什么
  47. return response.data;
  48. }, function (error) {
  49. // 对响应错误做点什么
  50. return Promise.reject(error);
  51. });
  52. /**
  53. * 远程请求
  54. * @type {{async: (function(*, *, *, *): Promise<unknown>), xhr_send: request.xhr_send, sync: (function(*, *, *, *): any)}}
  55. */
  56. const requestUtil = {
  57. xhr_send: function (xhr, method, headers, data) {
  58. if (headers) {
  59. for (const key in headers) {
  60. xhr.setRequestHeader(key, headers[key]);
  61. }
  62. }
  63. if (method.match(/^(POST|PUT)$/i)) {
  64. if (!headers || headers.indexOf("Content-Type") <= 0) {
  65. xhr.setRequestHeader('Content-Type', 'application/json');
  66. }
  67. xhr.send(JSON.stringify(data));
  68. } else {
  69. xhr.send();
  70. }
  71. },
  72. /**
  73. * 异步请求:requestUtil.async('https://jsonplaceholder.typicode.com/posts/1', 'GET', null, null)
  74. * .then(data => console.log(data))
  75. * .catch(error => console.error(error));
  76. */
  77. async: function (url, method, data, headers) {
  78. return new Promise((resolve, reject) => {
  79. const xhr = new XMLHttpRequest();
  80. xhr.open(method, url, true);
  81. this.xhr_send(xhr, method, headers, data);
  82. xhr.onload = () => {
  83. resolve(JSON.parse(xhr.responseText));
  84. };
  85. xhr.onerror = () => reject(xhr.statusText);
  86. });
  87. },
  88. /**
  89. * 拼接 url
  90. */
  91. buildUrl: function (url, params) {
  92. const urlObj = new URL(url);
  93. params.forEach(param => {
  94. urlObj.searchParams.set(param[0], param[1]);
  95. });
  96. return urlObj.toString();
  97. },
  98. /**
  99. * 同步请求 let a = request.sync("https://httpbin.tianyunperfect.cn/ip","GET",null,null)
  100. */
  101. sync: function (url, method, data, headers) {
  102. const xhr = new XMLHttpRequest();
  103. xhr.open(method, url, false);
  104. this.xhr_send(xhr, method, headers, data);
  105. return JSON.parse(xhr.responseText);
  106. }
  107. }
  108. /**
  109. * 休眠一段时间: await sleep(2000)
  110. * @param time
  111. * @returns {Promise<unknown>}
  112. */
  113. function sleep(time) {
  114. return new Promise((resolve) => setTimeout(resolve, time));
  115. }
  116. /**
  117. * 根据选择器 选择某一个dom,10秒钟内
  118. * @param sel
  119. * @returns {Promise<*>}
  120. */
  121. async function getDom(sel) {
  122. for (let i = 0; i < 100; i++) {
  123. let dom = document.querySelector(sel);
  124. if (dom) {
  125. return dom;
  126. } else {
  127. await sleep(100);
  128. }
  129. }
  130. }
  131. /**
  132. * 根据选择器 选择所有dom,10秒钟内
  133. * @param sel
  134. * @returns {Promise<*>}
  135. */
  136. async function getDomAll(sel) {
  137. for (let i = 0; i < 100; i++) {
  138. let dom = document.querySelectorAll(sel);
  139. if (dom.length > 0) {
  140. return dom;
  141. } else {
  142. await sleep(100);
  143. }
  144. }
  145. }
  146. /**
  147. * 添加全局样式: addGlobalStyle('.box {height: 100px !important;}');
  148. */
  149. function addGlobalStyle(newStyle) {
  150. let styleElement = document.getElementById('styles_js');
  151. if (!styleElement) {
  152. styleElement = document.createElement('style');
  153. styleElement.type = 'text/css';
  154. styleElement.id = 'styles_js';
  155. document.getElementsByTagName('head')[0].appendChild(styleElement);
  156. }
  157. styleElement.appendChild(document.createTextNode(newStyle));
  158. }
  159. /**
  160. * 获取 指定 name 的 url 参数
  161. * @param url
  162. * @param name
  163. * @returns {string|string}
  164. */
  165. function getQueryStringByUrl(url, name) {
  166. let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  167. let r = url.substring(url.indexOf('?') + 1).match(reg); //获取url中"?"符后的字符串并正则匹配
  168. let context = "";
  169. if (r != null)
  170. context = r[2];
  171. reg = null;
  172. r = null;
  173. return context == null || context === "" || context === "undefined" ? "" : decodeURI(context);
  174. }
  175. /**
  176. * 获取 指定 name 的 url 参数
  177. * @param name
  178. * @returns {string}
  179. */
  180. function getQueryString(name) {
  181. return getQueryStringByUrl(location.href, name);
  182. }
  183. // 随机数
  184. const randomUtil = {
  185. /**
  186. * 获取随机数
  187. * @param min
  188. * @param max
  189. * @returns {number}
  190. */
  191. getInt: function (min, max) {
  192. min = Math.ceil(min);
  193. max = Math.floor(max);
  194. return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
  195. },
  196. /**
  197. * 获取随机的一个值
  198. * @param arr
  199. * @returns {*}
  200. */
  201. getOneFromArray: function (arr) {
  202. return arr[this.getInt(0, arr.length)];
  203. }
  204. }
  205. /**
  206. * 创建一个<eleName k="attrs[k]">text</eleName>样式的页面元素
  207. * @param eleName
  208. * @param text
  209. * @param attrs
  210. * @returns {*}
  211. */
  212. function createEle(eleName, text, attrs) {
  213. let ele = document.createElement(eleName);
  214. // innerText 也就是 <p>text会被添加到这里</p>
  215. ele.innerText = text;
  216. // attrs 的类型是一个 map
  217. for (let k in attrs) {
  218. // 遍历 attrs, 给节点 ele 添加我们想要的属性
  219. ele.setAttribute(k, attrs[k]);
  220. }
  221. // 返回节点
  222. return ele;
  223. }
  224. /**
  225. * 自动关闭提示框
  226. * @param str 提示文本
  227. * @param sec 时间(秒)
  228. */
  229. function showMsg(str, sec) {
  230. const borderColor = "#336699"; //提示窗口的边框颜色
  231. const sWidth = document.body.offsetWidth;
  232. const sHeight = document.body.offsetHeight;
  233. //背景div
  234. const bgObj = document.createElement("div");
  235. let alertBgDiv = 'alertBgDiv';
  236. bgObj.setAttribute('id', alertBgDiv);
  237. bgObj.style.cssText = `position: fixed; top: 0; background: #E8E8E8; filter: progid:DXImageTransform.Microsoft.Alpha(style=3,opacity=25,finishOpacity=75; opacity: 0.6; left: 0; width: ${sWidth}px; height: ${sHeight}px; z-index: 10000`;
  238. document.body.appendChild(bgObj);
  239. //创建提示窗口的div
  240. const msgObj = document.createElement("div");
  241. let alertMsgDiv = "alertMsgDiv";
  242. msgObj.setAttribute("id", alertMsgDiv);
  243. msgObj.setAttribute("align", "center");
  244. msgObj.style.cssText = `background: white; border: 1px solid ${borderColor}; position: fixed; left: 50%; font: 15px/1.6em Verdana, Geneva, Arial, Helvetica, sans-serif; margin-left: -225px; top: ${document.body.scrollTop + (window.screen.availHeight / 2) - 150}px; text-align: center; line-height: 25px; z-index: 10001; min-width: 300px`;
  245. document.body.appendChild(msgObj);
  246. //提示信息标题
  247. const title = document.createElement("h4");
  248. let alertMsgTitle = "alertMsgTitle";
  249. title.setAttribute("id", alertMsgTitle);
  250. title.setAttribute("align", "left");
  251. title.style.cssText = `margin:0; padding:3px; background:${borderColor}; filter:progid:DXImageTransform.Microsoft.Alpha(startX=20, startY=20, finishX=100, finishY=100,style=1,opacity=75,finishOpacity=100); opacity:0.75; border:1px solid ${borderColor}; font:12px Verdana, Geneva, Arial, Helvetica, sans-serif; color:white`;
  252. title.innerHTML = "提示信息";
  253. document.getElementById(alertMsgDiv).appendChild(title);
  254. //提示信息
  255. const txt = document.createElement("p");
  256. txt.setAttribute("id", "msgTxt");
  257. txt.style.margin = "16px 0";
  258. txt.innerHTML = str;
  259. document.getElementById(alertMsgDiv).appendChild(txt);
  260. //设置关闭时间
  261. window.setTimeout(() => {
  262. document.body.removeChild(document.getElementById(alertBgDiv));
  263. document.getElementById(alertMsgDiv).removeChild(document.getElementById(alertMsgTitle));
  264. document.body.removeChild(document.getElementById(alertMsgDiv));
  265. }, sec * 1000);
  266. }
  267. /**
  268. * 打印信息
  269. * @param obj
  270. */
  271. function log(obj) {
  272. console.table(JSON.parse(JSON.stringify(obj)));
  273. }
  274. // 添加静态资源
  275. const staticLoader = {
  276. /**
  277. * 添加js引用 : addRemoteJs("https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js");
  278. */
  279. addRemoteJs: function (jsUrl) {
  280. if (document.querySelector(`script[src="${jsUrl}"]`)) {
  281. return;
  282. }
  283. const script = document.createElement('script');
  284. script.src = jsUrl;
  285. script.type = 'text/javascript';
  286. document.head.appendChild(script);
  287. },
  288. addRemoteCss: function (cssUrl) {
  289. if (document.querySelector(`link[href="${cssUrl}"]`)) {
  290. return;
  291. }
  292. const link = document.createElement('link');
  293. link.href = cssUrl;
  294. link.rel = 'stylesheet';
  295. link.type = 'text/css';
  296. document.head.appendChild(link);
  297. },
  298. /**
  299. * 添加 Jq
  300. */
  301. addJq: function () {
  302. const jqUrl = 'https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js';
  303. this.addRemoteJs(jqUrl);
  304. }
  305. }
  306. // 复制文本工具类
  307. const copyUtil = {
  308. /**
  309. * 复制,支持复制html: copyHtml('#wish_search_list .wish_s_item');
  310. * @param css_selector
  311. * @returns {Promise<void>}
  312. */
  313. copyFromSelector: async function (css_selector) {
  314. const el = document.querySelector(css_selector);
  315. const html = el.outerHTML;
  316. await this.copyFromHtml(html);
  317. },
  318. copyFromHtml: async function (html) {
  319. try {
  320. await navigator.clipboard.write([
  321. new ClipboardItem({
  322. 'text/html': new Blob([html], {type: 'text/html'})
  323. })
  324. ]);
  325. console.log('复制成功');
  326. } catch (err) {
  327. console.error('复制失败', err);
  328. }
  329. }
  330. }