UUID
function getGui(){ var S4 = function() { return(((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); }; return(S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4()); }
封装一个时间戳转日期的插件
const dateFormatter = (formatter, date) => { date = date ? new Date(date) : new Date(); const Y = date.getFullYear() + ''; const M = date.getMonth() + 1; const D = date.getDate(); const H = date.getHours(); const m = date.getMinutes(); const s = date.getSeconds(); return formatter .replace(/YYYY|yyyy/g, Y) .replace(/YY|yy/g, Y.substr(2, 2)) .replace(/MM/g, (M < 10 ? '0' : '') + M) .replace(/DD/g, (D < 10 ? '0' : '') + D) .replace(/HH|hh/g, (H < 10 ? '0' : '') + H) .replace(/mm/g, (m < 10 ? '0' : '') + m) .replace(/ss/g, (s < 10 ? '0' : '') + s); }; dateFormatter('YYYY-MM-DD HH:mm', '1995/02/15 13:55'); // 1995-02-15 13:55
正则的使用
// trim 的实现 str.replace(/(^\s+)|(\s+$)/g, ''); // 去掉回车换行 str.replace(/[\r\n]/g, ''); // 千位加 , 符号 '123456789'.replace(/(\d)(?=(\d{3})+$)/g, '$1,'); // "123,456,789" // 电话号码分割 '13012345678'.replace(/(\d)(?=(\d{4})+$)/g, '$1 '); // "130 1234 5678" // 创建模板引擎 function createTemplate(template) { return function(options) { return template.replace(/{{(.+?)}}/g, (str, key) => { return options[key] || ''; }); }; } const template = createTemplate('{{name}} gets {{stuff}} daily'); template({ name: 'Adam', stuff: 'radio' });
cookie
class CookieJar { set(name, value, days) { const date = new Date(); date.setDate(date.getDate() + days); document.cookie = `${name}=${value};expires=${date.toGMTString()};`; } get(name) { const reg = new RegExp(`${name}=(.+?);`); if (reg) { return reg[1]; } return null; } remove(name) { this.set(name, 1, -1); } }
url
// 获取地址栏 new URLSearchParams(location.search).get("name"); // "name" // 获取地址栏参数转对象格式 Object.fromEntries(new URLSearchParams(location.search)); // { ... } //Object.fromEntries()方法是Object.entries()的逆操作,用于将一个键值对数组转为对象。 const obj = { x: 42, y: 50 }; const tuple = Object.entries(obj); // [['x', 42], ['y', 50]] const reObj = Object.fromEntries(tuple); // { x: 42, y: 50 } new URLSearchParams(tuple).toString() // "x=42&y=50"
随机颜色
Math.floor(Math.random() * (2 << 23)).toString(16);
转义
function HTMLEncode(html) { var temp = document.createElement("div"); (temp.textContent != null) ? (temp.textContent = html) : (temp.innerText = html); var output = temp.innerHTML; temp = null; return output; } function HTMLDecode(text) { var temp = document.createElement("div"); temp.innerHTML = text; var output = temp.innerText || temp.textContent; temp = null; return output; } var tagText = "<p><b>123&456</b></p>"; var encodeText = HTMLEncode(tagText); console.log(encodeText); //<p><b>123&456</b></p> console.log(HTMLDecode(encodeText)); //<p><b>123&456</b></p>
复制输入框的内容
function copyVal(val,faDom) { var faDom = faDom || document.querySelector('body'); var div = document.createElement('div'); //不能display:none,会复制不到 div.style.cssText = `position:fixed;bottom:-99999px`; div.innerHTML = `<form name="copyValForm"><input name="beCopy" type="text" value="${val}" readonly="readonly" /></form>` document.querySelector('body').append(div); var btn = document.createElement('div') btn.className = "copyBtn"; btn.innerHTML="复制"; btn.addEventListener('click',function () { //不同进入光标也能选中 // document.form1.beCopy.focus(); document.copyValForm.beCopy.select(); document.execCommand("Copy"); document.copyValForm.beCopy.blur(); //复制后立刻离开光标,打断输入法弹出 timeMask('复制成功!') }) faDom.append(btn) }
滚动加载
// faDom一般是window,如果是另一个div,需要使用绝对定位才有属于div自己的独立滚动条 // sonDom如果不是填充满faDom,那sonDom一定要用padding填充到跟faDom一样的高度 // cb一定要有加载更多判断,比如一个全局变量,否则滚动一下会调用几十次请求 function addScroll(faDom,sonDom,cb) { $(faDom).on("scroll",function(){ // if($('#B').css('display')=='block'){ var windowHeight = $(faDom).height();//当前窗口的高度 var scrollTop = $(faDom).scrollTop();//当前滚动条从上往下滚动的距离 var docHeight = $(sonDom).height(); //当前文档的高度 // console.log( windowHeight,scrollTop,docHeight); //当 滚动条距底部的距离 + 滚动条滚动的距离 >= 文档的高度 - 窗口的高度 //换句话说:(滚动条滚动的距离 + 窗口的高度 = 文档的高度) 这个是基本的公式 if (scrollTop + windowHeight >= docHeight - 30) { console.log("===加载更多数据==="); if(flag && cb){ // flag是支持请求的标识 cb() } } // } }); }
上拉刷新
<article id="article"> <ul id="ul"> <li class="li" id="text">下拉刷新</li> <li class="li">1</li> <li class="li">2</li> <li class="li">3</li> ... </ul> </article> let ul = document.getElementById('ul'); // 获取ul列表 let div = document.getElementById('article') // 获取包裹ul列表的div(css: overflow:scroll;) let text = document.getElementById('text'); // 写着“下拉刷新”的元素 let start; // 辅助变量:触摸开始时,相对于文档顶部的Y坐标 let refresh = false; // 辅助变量:是否刷新 div.addEventListener('touchstart',function(event){ let touch = event.touches[0]; start = touch.pageY; // 辅助变量:触摸开始时,相对于文档顶部的Y坐标 },false); div.addEventListener('touchmove',function(event){ // 下拉刷新 let touch = event.touches[0]; if(div.scrollTop<=0){ // 如果ul列表到顶部,修改ul列表的偏移,显示“下拉刷新”,并准备触发下拉刷新功能,可自定义 ul.style.top = ul.offsetTop + touch.pageY - start +'px'; // ul.style.top = ul.offsetTop + 'px' start = touch.pageY; // 若ul偏移量过大,则修改文字,refresh置为true,配合'touchend'刷新 if(ul.offsetTop>=100) { text.innerHTML = "释放刷新"; refresh = true; } } },false); div.addEventListener('touchend',function(event){ // 若'touchend'时,ul偏移,用setInterval循环恢复ul的偏移量 if(ul.offsetTop>=0) { let time = setInterval(function(){ ul.style.top = ul.offsetTop -3 +'px'; // 若ul的偏移量恢复,clearInterval if(ul.offsetTop<=0){ clearInterval(time); text.innerHTML = "下拉刷新"; // 若恢复时'refresh===true',刷新页面 if(refresh){ location.reload(); } } }) } },false);
占位符
String.prototype.format = function() { if(arguments.length == 0) return this; var param = arguments[0]; var s = this; if(typeof(param) == 'object') { for(var key in param) s = s.replace(new RegExp("\\{" + key + "\\}", "g"), param[key]); return s; } else { for(var i = 0; i < arguments.length; i++) s = s.replace(new RegExp("\\{" + i + "\\}", "g"), arguments[i]); return s; } } console.log("http://{0}/{1}".format("www.songyanjun.net", "index.html")) console.log("http://{2}/{1}".format("www.songyanjun.net", "index.html",'1')) console.log("我叫{name},性别{sex},今年{age}岁".format({name: "美男子",sex: "男",age: 20}));
数组的排序
数字不能直接sort(),字母可以
let nums = [2, 3, 1]; //两个比较的元素分别为a, b nums.sort(function(a, b) { if(a > b) return 1; else if(a < b) return -1; else if(a == b) return 0; })
点击下载
var link = document.createElement('a'); link.setAttribute("download", "name"); link.href = "url"; link.click();
图片懒加载
图片懒加载在面试题二
瀑布流
就是很多图片排列成几列,每次添加都添加到高度最短的那一列
var arr = ["aa.png","bb.jpg",...] function LazyImg(arr){ if(arr.length!=0){ var url = arr.shift() var Img = new Image() Img.onload = function () { var LH = $('#left').height() var RH = $('#left').height() if(LH){ // append }else{ // append } } Img.src = url } }
来源:https://www.cnblogs.com/pengdt/p/12037985.html