util.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. * 同步请求 let a = request.sync("https://httpbin.tianyunperfect.cn/ip","GET",null,null)
  90. */
  91. sync: function (url, method, data, headers) {
  92. const xhr = new XMLHttpRequest();
  93. xhr.open(method, url, false);
  94. this.xhr_send(xhr, method, headers, data);
  95. return JSON.parse(xhr.responseText);
  96. }
  97. }
  98. /**
  99. * 休眠一段时间: await sleep(2000)
  100. * @param time
  101. * @returns {Promise<unknown>}
  102. */
  103. function sleep(time) {
  104. return new Promise((resolve) => setTimeout(resolve, time));
  105. }
  106. /**
  107. * 根据选择器 选择某一个dom,10秒钟内
  108. * @param sel
  109. * @returns {Promise<*>}
  110. */
  111. async function getDom(sel) {
  112. for (let i = 0; i < 100; i++) {
  113. let dom = document.querySelector(sel);
  114. if (dom) {
  115. return dom;
  116. } else {
  117. await sleep(100);
  118. }
  119. }
  120. }
  121. /**
  122. * 根据选择器 选择所有dom,10秒钟内
  123. * @param sel
  124. * @returns {Promise<*>}
  125. */
  126. async function getDomAll(sel) {
  127. for (let i = 0; i < 100; i++) {
  128. let dom = document.querySelectorAll(sel);
  129. if (dom.length > 0) {
  130. return dom;
  131. } else {
  132. await sleep(100);
  133. }
  134. }
  135. }
  136. /**
  137. * 添加全局样式: addGlobalStyle('.box {height: 100px !important;}');
  138. */
  139. function addGlobalStyle(newStyle) {
  140. let styleElement = document.getElementById('styles_js');
  141. if (!styleElement) {
  142. styleElement = document.createElement('style');
  143. styleElement.type = 'text/css';
  144. styleElement.id = 'styles_js';
  145. document.getElementsByTagName('head')[0].appendChild(styleElement);
  146. }
  147. styleElement.appendChild(document.createTextNode(newStyle));
  148. }
  149. /**
  150. * 获取 指定 name 的 url 参数
  151. * @param url
  152. * @param name
  153. * @returns {string|string}
  154. */
  155. function getQueryStringByUrl(url, name) {
  156. let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  157. let r = url.substring(url.indexOf('?') + 1).match(reg); //获取url中"?"符后的字符串并正则匹配
  158. let context = "";
  159. if (r != null)
  160. context = r[2];
  161. reg = null;
  162. r = null;
  163. return context == null || context === "" || context === "undefined" ? "" : decodeURI(context);
  164. }
  165. /**
  166. * 获取 指定 name 的 url 参数
  167. * @param name
  168. * @returns {string}
  169. */
  170. function getQueryString(name) {
  171. return getQueryStringByUrl(location.href, name);
  172. }
  173. // 随机数
  174. const randomUtil = {
  175. /**
  176. * 获取随机数
  177. * @param min
  178. * @param max
  179. * @returns {number}
  180. */
  181. getInt: function (min, max) {
  182. min = Math.ceil(min);
  183. max = Math.floor(max);
  184. return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
  185. },
  186. /**
  187. * 获取随机的一个值
  188. * @param arr
  189. * @returns {*}
  190. */
  191. getOneFromArray: function (arr) {
  192. return arr[this.getInt(0, arr.length)];
  193. }
  194. }
  195. /**
  196. * 创建一个<eleName k="attrs[k]">text</eleName>样式的页面元素
  197. * @param eleName
  198. * @param text
  199. * @param attrs
  200. * @returns {*}
  201. */
  202. function createEle(eleName, text, attrs) {
  203. let ele = document.createElement(eleName);
  204. // innerText 也就是 <p>text会被添加到这里</p>
  205. ele.innerText = text;
  206. // attrs 的类型是一个 map
  207. for (let k in attrs) {
  208. // 遍历 attrs, 给节点 ele 添加我们想要的属性
  209. ele.setAttribute(k, attrs[k]);
  210. }
  211. // 返回节点
  212. return ele;
  213. }
  214. /**
  215. * 自动关闭提示框
  216. * @param str 提示文本
  217. * @param sec 时间(秒)
  218. */
  219. function showMsg(str, sec) {
  220. const borderColor = "#336699"; //提示窗口的边框颜色
  221. const sWidth = document.body.offsetWidth;
  222. const sHeight = document.body.offsetHeight;
  223. //背景div
  224. const bgObj = document.createElement("div");
  225. let alertBgDiv = 'alertBgDiv';
  226. bgObj.setAttribute('id', alertBgDiv);
  227. 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`;
  228. document.body.appendChild(bgObj);
  229. //创建提示窗口的div
  230. const msgObj = document.createElement("div");
  231. let alertMsgDiv = "alertMsgDiv";
  232. msgObj.setAttribute("id", alertMsgDiv);
  233. msgObj.setAttribute("align", "center");
  234. 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`;
  235. document.body.appendChild(msgObj);
  236. //提示信息标题
  237. const title = document.createElement("h4");
  238. let alertMsgTitle = "alertMsgTitle";
  239. title.setAttribute("id", alertMsgTitle);
  240. title.setAttribute("align", "left");
  241. 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`;
  242. title.innerHTML = "提示信息";
  243. document.getElementById(alertMsgDiv).appendChild(title);
  244. //提示信息
  245. const txt = document.createElement("p");
  246. txt.setAttribute("id", "msgTxt");
  247. txt.style.margin = "16px 0";
  248. txt.innerHTML = str;
  249. document.getElementById(alertMsgDiv).appendChild(txt);
  250. //设置关闭时间
  251. window.setTimeout(() => {
  252. document.body.removeChild(document.getElementById(alertBgDiv));
  253. document.getElementById(alertMsgDiv).removeChild(document.getElementById(alertMsgTitle));
  254. document.body.removeChild(document.getElementById(alertMsgDiv));
  255. }, sec * 1000);
  256. }
  257. /**
  258. * 打印信息
  259. * @param obj
  260. */
  261. function log(obj) {
  262. console.table(JSON.parse(JSON.stringify(obj)));
  263. }
  264. // 添加静态资源
  265. const staticLoader = {
  266. /**
  267. * 添加js引用 : addRemoteJs("https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js");
  268. */
  269. addRemoteJs: function (jsUrl) {
  270. if (document.querySelector(`script[src="${jsUrl}"]`)) {
  271. return;
  272. }
  273. const script = document.createElement('script');
  274. script.src = jsUrl;
  275. script.type = 'text/javascript';
  276. document.head.appendChild(script);
  277. },
  278. addRemoteCss: function (cssUrl) {
  279. if (document.querySelector(`link[href="${cssUrl}"]`)) {
  280. return;
  281. }
  282. const link = document.createElement('link');
  283. link.href = cssUrl;
  284. link.rel = 'stylesheet';
  285. link.type = 'text/css';
  286. document.head.appendChild(link);
  287. },
  288. /**
  289. * 添加 Jq
  290. */
  291. addJq: function () {
  292. const jqUrl = 'https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js';
  293. this.addRemoteJs(jqUrl);
  294. }
  295. }
  296. // 复制文本工具类
  297. const copyUtil = {
  298. /**
  299. * 复制,支持复制html: copyHtml('#wish_search_list .wish_s_item');
  300. * @param css_selector
  301. * @returns {Promise<void>}
  302. */
  303. copyFromSelector: async function (css_selector) {
  304. const el = document.querySelector(css_selector);
  305. const html = el.outerHTML;
  306. await this.copyFromHtml(html);
  307. },
  308. copyFromHtml: async function (html) {
  309. try {
  310. await navigator.clipboard.write([
  311. new ClipboardItem({
  312. 'text/html': new Blob([html], {type: 'text/html'})
  313. })
  314. ]);
  315. console.log('复制成功');
  316. } catch (err) {
  317. console.error('复制失败', err);
  318. }
  319. }
  320. }