Javascript备忘录 2020-10-12 技巧 暂无评论 848 次阅读 攒了1年的轮子:yum: ``` /******************************************** 第一部分:异步函数 b64 = Base64.encode('str') 字符串转Base64 str = Base64.decode('b64') Base64转字符串(支持中文) arr.remove(val) 数组按值删元素 str = get_time() 获取时间 str = get_datetime() 获取日期时间 str = log(str) 在str之前添加日期时间 import_js(url) 给网页引用外部JavaScript dis(obj) 在显示对象的所有属性和方法 fake_click(obj) 模拟鼠标点击事件 save(filename,data) 保存数据 copy(str) 复制数据 *********************************************/ const Base64 = { encode: (str) => { return window.btoa(unescape(encodeURIComponent(str))) }, decode: (str) => { return decodeURIComponent(escape(window.atob(str))) } } Array.prototype.remove = function(val) { var index = this.indexOf(val); if (index > -1) { this.splice(index, 1); }}; function get_time() { var date = new Date; return date.getHours()+":"+date.getMinutes()+":"+date.getSeconds(); } function get_datetime() { var date = new Date; return date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds(); } function log(str) { var date = new Date; return date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds()+" -> "+str; } function import_js(url) { var importJs=document.createElement('script') importJs.setAttribute("type","text/javascript") importJs.setAttribute("src",url) document.getElementsByTagName("head")[0].appendChild(importJs) } function dis(obj) { for(i in obj){ if(typeof(obj[i])=='function') console.log('['+String(typeof(obj[i])).substr(0,3)+']'+i ) else console.log('['+String(typeof(obj[i])).substr(0,3)+']'+i +' = '+obj[i]) } } function fake_click(obj) { var ev = document.createEvent("MouseEvents"); ev.initMouseEvent( "click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null ); obj.dispatchEvent(ev); } function save(name, data) { if(typeof(data)=='object') data=JSON.stringify(data,null,4) var urlObject = window.URL || window.webkitURL || window; var downloadData = new Blob([data]); var save_link = document.createElementNS("http://www.w3.org/1999/xhtml", "a") save_link.href = urlObject.createObjectURL(downloadData); save_link.download = name; fake_click(save_link); } function copy(str) { let oInput = document.createElement('input') oInput.value = str document.body.appendChild(oInput) oInput.select() document.execCommand("Copy") oInput.style.display = 'none' document.body.removeChild(oInput) console.log('复制成功:'+str) } /******************************************** 第二部分:同步函数 file = await loadb64() 以Base64读取文件 str = await loadstr() 以字符串读取文件 obj = await loadobj() 读取Json文件 await sleep(ms) 延时ms毫秒 obj = await http_get(url) 发送Get请求 obj = await http_post(url,obj) 发送Post请求 ans = await fanyi('apple') 翻译 *********************************************/ async function loadb64() { return new Promise(function(resolve){ var input_elem = document.createElementNS("http://www.w3.org/1999/xhtml", "input") input_elem.setAttribute('type','file') input_elem.onchange = function(){ var filereader = new FileReader(); var fileType = this.files[0].type; filereader.onload = function(){ resolve(this.result) } filereader.readAsDataURL(this.files[0]); } fake_click(input_elem); }); } async function loadstr() { data=await loadb64() return Base64.decode(data.substr(data.indexOf(',')+1)) } async function loadobj() { data = await loadstr() return JSON.parse(data) } function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)) } async function http_get(url){ text = await fetch(url).then(function(response){return response.text()}) try{ var obj=JSON.parse(text); console.log(JSON.stringify(obj,null,4)) return obj; }catch{return text;} } async function http_post(url,obj){ text = await fetch(url,{ method: 'POST', body: JSON.stringify(obj), headers: new Headers({ 'Content-Type': 'application/json' }) }).then(function(response){return response.text()}) try{ var obj=JSON.parse(text); return obj; }catch{return text;} } async function fanyi(keyword) { if(keyword!=""){ if(typeof(md5)=='undefined') import_js('https://cdn.bootcdn.net/ajax/libs/blueimp-md5/1.0.1/js/md5.js') await sleep(1000) return new Promise(function(resolve){ var appid = '******************'; var key = '******************'; var salt = (new Date).getTime(); var query = keyword; var from = 'auto'; var to = 'auto'; var str1 = appid + query + salt +key; var sign = md5(str1); $.ajax({ url: 'https://fanyi-api.baidu.com/api/trans/vip/translate', type: 'get', dataType: 'jsonp', data: { q: query, appid: appid, salt: salt, from: from, to: to, sign: sign }, success: function (data) { resolve(data['trans_result'][0]["dst"]); } }); }); } return ""; } ``` 在11:59:58的时候,刷新网页 ``` var timeTask=setInterval(function(){ date=new Date(); h=date.getHours(); m=date.getMinutes(); s=date.getSeconds(); if(h==11&&m==59&&s==58){ location.reload() } },1000); ``` 在网页左侧,挂上自己的按钮: ``` function projsinit() { var projstool=document.createElement('div') projstool.setAttribute("style","position:fixed;left:10px;top:100px;z-index:99999;") projstool.setAttribute("id","projstool.proup.club") document.getElementsByTagName("body")[0].appendChild(projstool) styleEl = document.createElement('style') styleEl.innerText=" \ .projsbtn{ \ border: none; \ color: white; \ padding: 3px 5px; \ border-radius: 16px; \ text-align: center; \ text-decoration: none; \ display: inline-block; \ font-size: 14px; \ margin: 2px 2px; \ transition-duration: 0.4s; \ cursor: pointer; \ } \ .projsbtn.projsbtn-g{ \ background-color: white; \ color: black; \ border: 2px solid #4CAF50; \ } \ .projsbtn.projsbtn-g:hover { \ background-color: #4CAF50; \ color: white; \ } \ .projsbtn.projsbtn-b { \ background-color: white; \ color: black; \ border: 2px solid #008CBA; \ } \ \ .projsbtn.projsbtn-b:hover { \ background-color: #008CBA; \ color: white; \ } \ \ .projsbtn.projsbtn-r { \ background-color: white; \ color: black; \ border: 2px solid #f44336; \ } \ \ .projsbtn.projsbtn-r:hover { \ background-color: #f44336; \ color: white; \ } \ \ .projsbtn.projsbtn-w { \ background-color: white; \ color: black; \ border: 2px solid #e7e7e7; \ } \ \ .projsbtn.projsbtn-w:hover { \ background-color: #e7e7e7; \ } \ \ .projsbtn.projsbtn-k { \ background-color: white; \ color: black; \ border: 2px solid #555555; \ } \ .projsbtn.projsbtn-k:hover { \ background-color: #555555; \ color: white; \ } \ "; document.head.appendChild(styleEl); return projstool; } function projsbtn(text='button',func='console.log("click\ncolor:r,g,b,k,w")',color='g') { let projstool=document.getElementById('projstool.proup.club') if(projstool==null) projstool=projsinit() let btn=document.createElement('button') btn.setAttribute("class","projsbtn projsbtn-"+color) btn.setAttribute("onclick",func) btn.innerText=text projstool.appendChild(btn) let br=document.createElement('br') projstool.appendChild(br) return btn; } /* 使用示例 */ function test(){ console.log("test"); } projsbtn('点我','test()','r') projsbtn('点我1111','test()','g') projsbtn('点我2222222222','test()','b') projsbtn('点我','test()','w') projsbtn('点我','test()','k') ``` 标签: 备忘录 本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。
评论已关闭