//替代绑定模板数据________________________ .replace(/{形参}/g, 实参); html += tpl .replace(/{形参}/g, 实参);
//for循环________________________ var arr = for (var i = 0, len = arr.length; i < len; i++) { var a = arr[i]; } var arr =, html = '', tpl = '{形参}'; for (var i = 0, len = arr.length; i < len; i++) { var a = arr[i]; html += tpl .replace(/{形参}/g, 实参) .replace(/{形参}/g, 实参); } DOM.innerHTML = html;
//Axios读取后台数据________________________ var params = {参数名: "参数值"}; this.$axios.get("接口路径", {params: params}).then(r => { r = r.data; if (r.status == "SUCCESS") { r = r.data; if (r) {/*这里写代码*/ /* this.items = r;*/ } } else { alert(r.message); } }).catch(e => { console.log("【接口报错】", e); });
//将数字转换为保留2位有效数字的百分数________________________ var value = 0.0251; value = parseFloat((value * 100).toFixed(2)) + '%'; alert(value);
/*验证用户名输入*/ onkeyup = "this.value=this.value.replace(/\ |\ |[^\x00-\x80]/g,'')"
//自定义控制台显示样式________________________ var msg = '提内内容'; console.log('%c报错信息:','background:red;color:white;padding:5px;border-radius:5px;',msg);
//Vue常用读取后台接口方法________________________ var params = {参数名: "参数值"}; this.$axios.get("接口路径", {params: params}).then(r => { r = r.data; if (r.status == "SUCCESS") { r = r.data; if (r) {/*这里写代码*/ /* this.items = r;*/ } } else { console.log('%c报错信息', 'background:red;color:white;padding:5px;border-radius:5px;',r.message); } }).catch(e => { console.log("【接口报错】", e); });
.shadow { /*穿透阴影效果兼容各种浏览器*/ -webkit-filter: drop-shadow(5px 10px 20px rgba(0, 0, 0, .5)); filter: drop-shadow(5px 10px 20px rgba(0, 0, 0, .5)); -ms-filter: "progid:DXImageTransform.Microsoft.Dropshadow(OffX=5, OffY=10, Color='#CCC')"; filter: "progid:DXImageTransform.Microsoft.Dropshadow(OffX=5, OffY=10, Color='#CCC')"; }
@media screen and (max-width: 1260px) { .div { /**适应1280x800的屏幕,除去浏览器滚动条宽度20px*/ } } @media screen and (min-width: 1261px) and (max-width: 1346px) { .div { /**适应1366x768的屏幕,除去浏览器滚动条宽度20px*/ } } @media screen and (min-width: 1347px) and (max-width: 1420px) { .div { /**适应1440x900的屏幕,除去浏览器滚动条宽度20px*/ } } @media screen and (min-width: 1421px) and (max-width: 1900px) { .div { /**适应1920x1080的屏幕,除去浏览器滚动条宽度20px*/ } } @media screen and (min-width: 1901px) { .div { /**适应宽度超过1920的屏幕,除去浏览器滚动条宽度20px*/ } } @media screen and (max-height: 668px) { .div { /**适应1366x768的屏幕,除去浏览器菜单栏、标签栏、状态栏以及系统任务栏高度100px*/ } } @media screen and (min-height: 669px) and (max-height: 800px) { .div { /**适应1440x900的屏幕,除去浏览器菜单栏、标签栏、状态栏以及系统任务栏高度100px*/ } } @media screen and (min-height: 801px) and (max-height: 980px) { .div { /**适应1920x1080的屏幕,除去浏览器菜单栏、标签栏、状态栏以及系统任务栏高度100px*/ } } @media screen and (min-height: 981px) { .div { /**适应高度超过1080的屏幕,除去浏览器菜单栏、标签栏、状态栏以及系统任务栏高度100px*/ } }
<link rel="stylesheet" type="text/css" media="screen and (max-device-width:768px)" href="css/手机.css"> <link rel="stylesheet" type="text/css" media="screen and (min-device-width:769px)" href="css/电脑.css">
/**禁止拖拽保存图片*/function donotDrag() { window.ondragstart = window.ontouchmove = document.ondragstart = document.ontouchmove = function (e) { e.preventDefault(); return false; }; }
<!--获取外网IP--> <!--<script src="http://ip.chinaz.com/getip.aspx"></script>--> <script src="http://pv.sohu.com/cityjson?ie=utf-8"></script> <script> document.write('您的外网IP:' + returnCitySN["cip"] + '<br>您的邮编:' + returnCitySN["cid"] + '<br>您所在城市:' + returnCitySN["cname"]);</script>
$(function(){ }) $().ready(function(){ }) $(document).ready(function(){ }) $(window).load(function(){ })
.animate-name { animation: animate-name .618s linear infinite; -moz-animation: animate-name .618s linear infinite; /** Firefox */ -webkit-animation: animate-name .618s linear infinite; /** Safari 和 Chrome */ -o-animation: animate-name .618s linear infinite; /** Opera */ } @keyframes animate-name { 0% { transform: rotate(0deg); } 50% { transform: rotate(180deg); } 100% { transform: rotate(360deg); } } @-moz-keyframes animate-name { 0% { -moz-transform: rotate(0deg); } 50% { -moz-transform: rotate(180deg); } 100% { -moz-transform: rotate(360deg); } } @-webkit-keyframes animate-name { 0% { -webkit-transform: rotate(0deg); } 50% { -webkit-transform: rotate(180deg); } 100% { -webkit-transform: rotate(360deg); } } @-ms-keyframes animate-name { 0% { -ms-transform: rotate(0deg); } 50% { -ms-transform: rotate(180deg); } 100% { -ms-transform: rotate(360deg); } } @-o-keyframes animate-name { 0% { -o-transform: rotate(0deg); } 50% { -o-transform: rotate(180deg); } 100% { -o-transform: rotate(360deg); } }
div { -webkit-transform: translateY(-5px); /* for Chrome || Safari */ -moz-transform: translateY(-5px); /* for Firefox */ -ms-transform: translateY(-5px); /* for IE */ -o-transform: translateY(-5px); /* for Opera */ transform: translateY(-5px); }
*:not([class*=layui-layer]), :before, :after, :visited, :focus, :focus-within, :checked { transition: .382s; /** IE 9 */ -moz-transition: .382s; /** Firefox 4 */ -webkit-transition: .382s; /** Safari 和 Chrome */ -o-transition: .382s; /** Opera */ -khtml-transition: .382s; /** only Safari */ }
div { transition: .382s; -moz-transition: .382s; -webkit-transition: .382s; -o-transition: .382s; -khtml-transition: .382s; }
/*自定义选择内容样式*/ ::selection { background: rgba(82, 170, 255, .3); color: #2366bd; } ::-moz-selection { background: rgba(82, 170, 255, .3); color: #2366bd; } ::-webkit-selection { background: rgba(82, 170, 255, .3); color: #2366bd; }
/*滚动条轨道*/ ::-webkit-scrollbar { width: 8px; background: rgba(255, 255, 255, 0.2); } /*滚动条滑块*/ ::-webkit-scrollbar-thumb { border-radius: 8px; background: rgba(255, 255, 255, 0.2); } /*移入滑块*/ ::-webkit-scrollbar-thumb:hover { background: rgba(255, 255, 255, 0.4); }
var url = "http://www.shuzhiqiang.com/api"; var data = {start: 0, count: 1}; $.ajax({ type: "POST", url: url, data: data, success: function (data) { if (data.code == 200) { console.log(data); document.write(JSON.stringify(data)); } else { console.log("报错", data); } }, error: function (e) { console.log(e); } });
$.ajax({ type: "GET", url: "http://www.shuzhiqiang.com/api", data: {username: "admin", password: "123456"}, success: function (data) { document.write(JSON.stringify(data)); }, error: function (e) { console.log(e); } })
/**jsonp方式获取数据*/ $.ajax({ type: "POST", url: "http://www.shuzhiqiang.com/api", data: {method: "originateCollectByDay", startDate: "2017-05-01", endDate: "2017-07-01"}, dataType: "jsonp", jsonp: 'callback', success: function (data) { alert(data[0].originate); } })
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <script> $.get("http://www.w3school.com.cn/example/jquery/demo_test.asp&id=1", function (data, status) { alert("数据:" + data + "\n状态:" + status); }); </script>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <script> $.post("http://www.w3school.com.cn/example/jquery/demo_test.asp", {name: "Donald Duck", city: "Duckburg"}, function (data, status) { alert("Data: " + data + "\nStatus: " + status); }); </script>
/**postJSON自定义方法*/ var postJSON = function (url, data, success) { typeof data == "function" && (success = data, data = {}); typeof data == "undefined" || typeof data == "null" && (success = function () { }, data = {}); return $.ajax({ type: "POST", contentType: "application/x-www-form-urlencoded;application/json; charset=utf-8", /**这个里面的application/x-www-form-urlencoded如果去掉,Tomcat的HttpServletRequest类request.getParameter(name)将无法获取数据*/ dataType: "jsonp", jsonp: "callback", url: url, data: data, success: success }); }; /**调用postJSON*/$.postJSON("http://www.shuzhiqiang.com/api", {username: "admin", password: "123456"}, function (data) { console.log(data); });
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <script> /**getJSON方法:jQuery读取jsonp格式数据,在 jQuery 1.2 中,您可以通过使用 JSONP 形式的回调函数来加载其他网域的 JSON 数据,如 "myurl?callback=?"。jQuery 将自动替换 ? 为正确的函数名,以执行回调函数。 注意:此行以后的代码将在这个回调函数执行前执行。*/ $.getJSON("http://www.shuzhiqiang.com/api?parameter=1" + "&callback=?", function (data) { console.log(data); }).success(function () { /**alert("success");*/ }).error(function () { /**alert("error");*/ }).complete(function () { /**alert("complete");*/ }).done(function () { /**从jQuery 1.8开始不支持success回调函数*/ /**alert('成功');*/ }).fail(function () {/**从jQuery 1.8开始不支持error回调函数*/ /**alert('失败')*/ }).always(function () { /**从jQuery 1.8开始不支持complete回调函数*/ /**alert('完成');*/ }); </script>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <script> /**getJSON方法:jQuery读取jsonp格式数据,在 jQuery 1.2 中,您可以通过使用 JSONP 形式的回调函数来加载其他网域的 JSON 数据,如 "myurl?callback=?"。jQuery 将自动替换 ? 为正确的函数名,以执行回调函数。 注意:此行以后的代码将在这个回调函数执行前执行。*/ $.getJSON("http://www.shuzhiqiang.com/api?parameter=1" + "&callback=?", function (data) { console.log(data); }).success(function () { /**alert("success");*/ }).error(function () { /**alert("error");*/ }).complete(function () { /**alert("complete");*/ }).done(function () { /**从jQuery 1.8开始不支持success回调函数*/ /**alert('成功');*/ }).fail(function () {/**从jQuery 1.8开始不支持error回调函数*/ /**alert('失败')*/ }).always(function () { /**从jQuery 1.8开始不支持complete回调函数*/ /**alert('完成');*/ }); </script>
/*径向渐变合集----------------------------------------------------------------*/ /* closest-side */ .closest-side .circle { background-image: -webkit-radial-gradient(closest-side circle at 50% 90%, transparent, black); background-image: -o-radial-gradient(closest-side circle at 50% 90%, transparent, black); background-image: -moz-radial-gradient(closest-side circle at 50% 90%, transparent, black); background-image: radial-gradient(closest-side circle at 50% 90%, transparent, black); } .closest-side .ellipse { background-image: -webkit-radial-gradient(closest-side ellipse at 50% 90%, transparent, black); background-image: -o-radial-gradient(closest-side ellipse at 50% 90%, transparent, black); background-image: -moz-radial-gradient(closest-side ellipse at 50% 90%, transparent, black); background-image: radial-gradient(closest-side ellipse at 50% 90%, transparent, black); } /* closest-corner */ .closest-corner .circle { background-image: -webkit-radial-gradient(closest-corner circle at 50% 90%, transparent, black); background-image: -o-radial-gradient(closest-corner circle at 50% 90%, transparent, black); background-image: -moz-radial-gradient(closest-corner circle at 50% 90%, transparent, black); background-image: radial-gradient(closest-corner circle at 50% 90%, transparent, black); } .closest-corner .ellipse { background-image: -webkit-radial-gradient(closest-corner at 50% 90%, transparent, black); background-image: -o-radial-gradient(closest-corner at 50% 90%, transparent, black); background-image: -moz-radial-gradient(closest-corner at 50% 90%, transparent, black); background-image: radial-gradient(closest-corner ellipse at 50% 90%, transparent, black); } /* farthest-side */ .farthest-side .circle { background-image: -webkit-radial-gradient(farthest-side circle at 50% 90%, transparent, black); background-image: -o-radial-gradient(farthest-side circle at 50% 90%, transparent, black); background-image: -moz-radial-gradient(farthest-side circle at 50% 90%, transparent, black); background-image: radial-gradient(farthest-side circle at 50% 90%, transparent, black); } .farthest-side .ellipse { background-image: -webkit-radial-gradient(farthest-side ellipse at 50% 90%, transparent, black); background-image: -o-radial-gradient(farthest-side ellipse at 50% 90%, transparent, black); background-image: -moz-radial-gradient(farthest-side ellipse at 50% 90%, transparent, black); background-image: radial-gradient(farthest-side ellipse at 50% 90%, transparent, black); } /* farthest-corner */ .farthest-corner .circle { background-image: -webkit-radial-gradient(farthest-corner circle at 50% 90%, transparent, black); background-image: -o-radial-gradient(farthest-corner circle at 50% 90%, transparent, black); background-image: -moz-radial-gradient(farthest-corner circle at 50% 90%, transparent, black); background-image: radial-gradient(farthest-corner circle at 50% 90%, transparent, black); } .farthest-corner .ellipse { background-image: -webkit-radial-gradient(farthest-corner ellipse at 50% 90%, transparent, black); background-image: -o-radial-gradient(farthest-corner ellipse at 50% 90%, transparent, black); background-image: -moz-radial-gradient(farthest-corner ellipse at 50% 90%, transparent, black); background-image: radial-gradient(farthest-corner ellipse at 50% 90%, transparent, black); }
<script> /**仿ios弹窗样式*/ function showIosLayer(content, time, shade, shadeClose, completeFun, getIndex) { time = time == undefined || time == null ? 3 : time; shade || (shade = [.4, 'black']); completeFun = completeFun || function () { }; var index = layer.msg(content, {time: time * 1000, shade: shade, shadeClose: Boolean(shadeClose), skin: 'SG-layer-skin'}, completeFun); getIndex && getIndex(index); /**设置快捷键*/ document.onkeyup = function (e) { var k = e.keyCode || e.which || e.charCode; /**独立键*/ if (k == 37 || k == 38 || k == 27 || k == 8) { /*按下 ← ↑ Esc <BACKSAPCE 的时候执行*/ index && top.layer.close(index); } }; } /**防止关闭模态窗体*/ function showForbidVisitAlert() { showIosLayer("舒工温馨提示您:<br>该页面暂不支持移动端访问,请用电脑访问😊", 0, [1, "white"], false); } </script> <style> /**SG-layer-skin.css的样式为:*/ body .layui-layer-msg { width: 75%; height: auto; font-family: 'Microsoft YaHei', 'PingFangSC-Regular', 'sans-serif', 'San Francisco', 'Microsoft Sans Serif', 'Arial'; text-align: justify; color: dimgray; border-radius: 1em; border: none; box-shadow: 0 1em 2.5em rgba(0, 0, 0, .382); background: white; } </style>
<!--热区--> <img src="https://www.baidu.com/img/bd_logo1.png" usemap="#hot-area-map"> <!--如果不希望出现点击的边框热区,去掉usemap的#--> <map name="hot-area-map"> <area shape="rect" coords="20,20,80,80" href="#rect"> <area shape="circle" coords="200,50,50" href="#circle"> <area shape="poly" coords="150,100,200,120,180,130,190,180,150,150,100,160,140,120,100,110" href="#poly"> </map>
<!--百度获取地理信息坐标--> <script src="http://api.map.baidu.com/api?v=2.0&ak=3k1MmoM9pAO0SMrlqe9qKhICi0cbo2TE"></script> <!--上面这个百度APIkey密钥是用百度ID:155****3322注册的,如果要更改密钥权限找舒工!--> <script> var baiduGEO = { getPosition: function (success, error) { var g = new BMap.Geolocation(); /*开启SDK辅助定位*/ g.enableSDKLocation(); g.getCurrentPosition(function (p) { /*p.point.lng|p.point.lat*/ this.getStatus() == BMAP_STATUS_SUCCESS ? success(p) : (error && error(p, this.getStatus())); }); }, getDistance: function (from, to) { return new BMap.Map().getDistance(new BMap.Point(from.lng, from.lat), new BMap.Point(to.lng, to.lat)); } }; /*测试用例*/ console.log(baiduGEO.getDistance({lng: 116.127214, lat: 24.306139}, {lng: 116.127443, lat: 24.306204})); </script>
<!--腾讯获取地理信息坐标--> <script src="https://apis.map.qq.com/tools/geolocation/min?key=6NMBZ-E4YL6-XF4SR-M75G4-FXCHE-FQBLL&referer=myapp"></script> <script src="https://map.qq.com/api/js?v=2.exp&key=6NMBZ-E4YL6-XF4SR-M75G4-FXCHE-FQBLL"></script> <!--上面这个腾讯APIkey密钥是腾讯ID:155****3322注册的,如果要更改密钥权限找舒工!--> <script> var tencentGEO = { _key: '6NMBZ-E4YL6-XF4SR-M75G4-FXCHE-FQBLL', /*如果不能使用去https://lbs.qq.com/console/setting.html?key=6NMBZ-E4YL6-XF4SR-M75G4-FXCHE-FQBLL设置绑定IP白名单*/ getPosition: function (success, error, timeout) { /*lng,lat,province,city,district|区,addr|最近地址名称,nation|国家,adcode|邮政编码,accuracy|位置误差(米)*/ new qq.maps.Geolocation(this._key, "myapp").getLocation(success, error, {timeout: timeout || 10 * 1000}); /*设置定位超时10秒钟 }*/ }, getDistance: function (from, to, success) { $.getJSON('https://apis.map.qq.com/ws/distance/v1/?mode=driving&output=jsonp&callback=?&from=' + from.lat + ',' + from.lng + '&to=' + to.lat + ',' + to.lng + '&key=' + this._key, function (d) { success(d.result.elements[0].distance); }); } }; /*测试用例*/ tencentGEO.getDistance({lng: 116.127214, lat: 24.306139}, {lng: 116.127443, lat: 24.306204}, function (d) { console.log(d); }); </script>
微信浏览器的UserAgent Mozilla/5.0 (Linux; Android 8.0; MI 6 Build/OPR1.170623.027; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/57.0.2987.132 MQQBrowser/6.2 TBS/044203 Mobile Safari/537.36 MicroMessenger/6.6.7.1321(0x26060739) NetType/WIFI Language/zh_CN
/**原生JS实现jQuery的ready方法*/ function ready(fn) { var d = document; if (d.addEventListener) {/*标准浏览器*/ d.addEventListener('DOMContentLoaded', function () {/*注销事件,避免反复触发*/ d.removeEventListener('DOMContentLoaded', arguments.callee, false); /*执行函数*/ fn(); }, false); } else if (d.attachEvent) {/*IE浏览器*/ d.attachEvent('onreadystatechange', function () { if (d.readyState == 'complete') { d.detachEvent('onreadystatechange', arguments.callee); /*执行函数*/ fn(); } }); } } /*测试用例*/ ready(function () { alert("在加载完DOM(不包含图片等非文字媒体文件)之后,onload之前执行!") })
var scroll = { id: null, scrollTop: function () { return document.body.scrollTop || document.documentElement.scrollTop || window.pageYOffset || 0; }, width: function () { var d = document.createElement('div'), s = {width: '100px', height: '100px', overflowY: 'scroll'}, i, w; for (i in s) d.style[i] = s[i]; document.body.append(d), w = d.offsetWidth - d.clientWidth, d.remove(); return w; }, twTo: function (y) { /*<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/2.0.2/TweenMax.min.js"><\/script>*/ /* TweenMax.to("html", 1, {scrollTop: y, ease: Strong.easeOut});*/ $("html").stop().animate({scrollTop: y}); }, to: function (y) { function stopScroll() { scroll.id && clearInterval(scroll.id); } stopScroll(); scroll.id = setInterval(function () { moveScroll(y); }, 1); function moveScroll(Y, R) { Y || (Y = 0); R || (R = .0382); var st = scroll.scrollTop(); st += (Y - st) * R; window.scrollTo(0, st); st == Y && stopScroll(); } window.onmousewheel = document.onmousewheel = document.onkeyup = window.onkeyup = function () { stopScroll(); }; } }; /*测试用例*/ scroll.to(2000);
<!--邮箱后缀自动补全功能:可以多个邮箱输入框遍历(datalist必须要紧接在inut后面)--> <input list="inputDropDownList" placeholder="请输入邮箱"/> <datalist id="inputDropDownList"></datalist> <script type="text/javascript"> function inputMailList(sel) { var mails = ["@qq.com", "@sina.com", "@163.com", "@126.com", "@yahoo.com.cn", "@gmail.com", "@sohu.com"]; sel = typeof sel == "string" ? document.querySelectorAll(sel) : [sel]; var arr = sel; for (var i in arr) { var a = arr[i]; a.oninput = a.onchange = function () { var key = this.value, html = ""; key = key.indexOf("@") > -1 ? key.slice(0, key.indexOf("@")) : key; for (var k in mails) { html += '<option value="' + key + mails[k] + '"></option>'; } (this.nextElementSibling || this.nextSibling).innerHTML = (html); } } } inputMailList("input"); </script>
/**原生Ajax*/ function ajax() { var a = arguments[0]; var d = { t: a.type || "GET", u: a.url || "", a: a.async || "true", d: a.data || null, dt: a.dataType || "text", ct: a.contentType || "application/x-www-form-urlencoded", b: a.beforeSend || function () { }, s: a.success || function () { }, e: a.error || function () { } }; d.b(); var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"); xhr.responseType = d.dt; xhr.open(d.t, d.u, d.a); xhr.setRequestHeader("Content-Type", d.ct); xhr.send(JSON.stringify(d.d).replace(/\t|\n|\r|\"|\{|\}/g, "").replace(/,/g, "&").replace(/:/g, "=")); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if (xhr.status == 200) { d.s(xhr.response) } else { d.e() } } } }; /*测试用例*/ ajax({ type: "POST", url: "http://www.shuzhiqiang.com/api", dataType: "json", data: {start: 0, count: 5}, beforeSend: function (e) { console.log("开始加载…"); }, success: function (msg) { console.log(msg) }, error: function (e) { console.log(e) } })
【整理】【精华】【实用】常用代码片段(二)https://developer.aliyun.com/article/1476776