util.js 11 KB

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