util.js 10 KB

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