[TOC] ## 方法 ### 打印时间戳 ``` now = + new Date() console.log(now) //1578561258234 ``` ### 原生点击提示信息 ``` function bh_msg_tips(msg){ var oMask = document.createElement("div"); oMask.id = "bh_msg_lay"; oMask.style.position="fixed"; oMask.style.left="0"; oMask.style.top="50%"; oMask.style.zIndex="100"; oMask.style.textAlign="center"; oMask.style.width="100%"; oMask.innerHTML = "<span style='background: rgba(0, 0, 0, 0.65);color: #fff;padding: 10px 15px;border-radius: 3px; font-size: 14px;'>" + msg + "</span>"; document.body.appendChild(oMask); setTimeout(function(){$("#bh_msg_lay").remove();},2000); } ``` ### 自定义去除字符 ``` String.prototype.OkTrim=function (tag) { var notreg = '^\\/()'; if (notreg.indexOf(tag)!=-1){ tag = '\\'+tag; } var reg =new RegExp('^'+tag+'|'+tag+'$','g'); return this.replace(reg,''); } '^asdasd^'.OkTrim('^'); //asdasd "hello word he".OkTrim('he'); //llo word ``` ### 平滑滚动到顶部 ``` var scrollSmoothTo = function (position) { if (!window.requestAnimationFrame) { window.requestAnimationFrame = function(callback, element) { return setTimeout(callback, 17); }; } // 当前滚动高度 var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; // 滚动step方法 var step = function () { // 距离目标滚动距离 var distance = position - scrollTop; // 目标滚动位置 scrollTop = scrollTop + distance / 5; if (Math.abs(distance) < 1) { window.scrollTo(0, position); } else { window.scrollTo(0, scrollTop); requestAnimationFrame(step); } }; step(); }; //使用 scrollSmoothTo(100) ``` ### 原生图片懒加载 ``` var bodyScrollHeight = document.body.scrollTop;// body滚动高度 var windowHeight = window.innerHeight;// 视窗高度 var imgs = document.getElementsByClassName('lazyloadimg'); for (var i =0; i < imgs.length; i++) { var imgHeight = imgs[i].offsetTop;// 图片距离顶部高度 if (imgHeight < windowHeight + bodyScrollHeight) { imgs[i].src = imgs[i].getAttribute('data-src'); img[i].className = img[i].className.replace('lazyloadimg','') } } } ``` ### 图片放大 ``` <img onclick='bigviewimg(this)' > function bigviewimg(img) { var url = $(img).data('url') var htmlText='<div onclick="this.style.display=\'none\'" class="img_show" style=" position: absolute;; bottom: 40px; top:40px; left: 40px; right: 40px; background-color: #000000; text-align: center; z-index:999999; border: 2px solid #fff;">\n' + ' </div> <img style=" max-width: 100%; position: absolute; top: 50%; left:50%; transform:translate(-50%,-50%)" src="'+url+'" alt=""></div>' $('body').append(htmlText) } ``` ### 转义/反转义 html 转义 ``` function escapeHTML(a){ a = "" + a; return a.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");; }, ``` 反转义 ``` function unescapeHTML(a) { a = "" + a; return a.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&").replace(/&quot;/g, '"').replace(/&apos;/g, "'"); } ```