//替代绑定模板数据________________________
.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>
/*径向渐变合集----------------------------------------------------------------*/
/* 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>
var browser = {
/**浏览器可视区域宽度高度(不含纵向滚动条宽度和水平滚动条高度)*/ visibleWidth: function () {
return document.documentElement.clientWidth || document.body.clientWidth
}, visibleHeight: function () {
return document.documentElement.clientHeight || document.body.clientHeight
}, update: function () {
/**升级浏览器*/ var s = this.version(), b = s.browser, v = s.version.split('.')[0], a = function () {
alert('朋友!\n您还在用大家都抛弃了的浏览器版本吗?\n淘宝都不支持这个浏览器了!\n还是点击确定更新下吧!\n与世界接轨很有必要!\n祝您早日富可敌国!');
location.replace("https://down.360safe.com/se/360se_setup.exe");
};
b == "chrome" && v < 55 && a();
b == "firefox" && v < 60 && a();
b == "msie" && v < 10 && a();
b == "opera" && v < 55 && a();
/*document.write(b + "的版本是" + s.version);*/
}, version: function () {
/**获取浏览器版本*/ var s = {}, m = navigator.userAgent.toLocaleLowerCase().match(/(msie|firefox|chrome|opera|version).*?([\d.]+)/);
s.browser = m[1].replace(/version/, "'safari"), s.version = m[2];
return s;
}
};
/*测试用例*/
broswer.update();
<!--热区-->
<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)
}
})
/**路径修复:因更换服务器图片路径指向错误的问题*/ var pathRepair = {
__r: function (p, o, n) {
return p.replace(new RegExp(o, "g"), n);
}, __getImgSrc: function (html) {
var imgReg = /<img.*?(?:>|\/>)/gi, srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i, arr = html.match(imgReg), srcs = [];
if (arr) {
for (var i = 0; i < arr.length; i++) {
var src = arr[i].match(srcReg), src = src[1];
src && srcs.push(src)
}
return srcs;
} else {
return null;
}
}, __addSlash: function (a) {
return (a.indexOf("/") == 0 ? "" : "/") + a;
}, replace: function (path, oldUrlOrArr, newUrl) {
oldUrlOrArr instanceof Array || (oldUrlOrArr = [oldUrlOrArr]);
var arr = oldUrlOrArr;
for (var i in arr) var a = arr[i], path = this.__r(path, a, newUrl);
return path;
}, img: function (imgUrl, oldUrl, newUrl, http) {
if (!imgUrl) return;
http || (http = 'http://'), imgUrl.indexOf(http) == -1 && (imgUrl = http + newUrl + this.__addSlash(imgUrl));
return pathRepair.replace(imgUrl, oldUrl, newUrl);
}, detail: function (html, oldUrlOrArr, newUrl, http) {
if (!html) return;
http || (http = 'http://');
var arr = this.__getImgSrc(html), r = [];
if (arr) {
for (var i = 0, len = arr.length; i < len; i++) {
var a = arr[i];
a.indexOf(http) == -1 && (a = http + newUrl + this.__addSlash(a));
var b = this.replace(a, oldUrlOrArr, newUrl);
r[i] = b;
}
for (i = 0; i < len; i++) {
var a = arr[i], b = r[i], html = this.__r(html, a, b);
}
}
return html;
}
};
/*测试用例*/
console.log(pathRepair.detail(html, "121.40.143.145", "www.shuzhiqiang.com", "http://"));
/**选项卡切换效果神器1.0*/ var chooseBar = {
_ac: "active", _bar: null, _con: null, _fun: null, __reset: function () {
this._bar.forEach(function (e) {
e.className = e.className.replace(new RegExp(chooseBar._ac, "g"), "").replace(/ /g, "");
e.style.cursor = "pointer";
});
this._con && (this._con.forEach(function (e) {
e.style.display = "none";
}));
}, __active: function (i) {
i || (i = 0), this.__reset();
var b = this._bar[i];
b.className += " " + this._ac, b.style.cursor = "default";
this._con && (this._con[i].style.display = "block");
this._fun && this._fun(i);
}, click: function (obj) {
this.init(obj, 'click');
}, over: function (obj) {
this.init(obj, 'over');
}, init: function (obj, type) {
/**obj的格式说明: { bar:[(必填)按钮的id or class(数组)], con:[(必填)显示内容的id or class(数组)], } 特别说明:在选项卡上面加入.active{ 高亮显示样式 }; */ this._bar = obj.bar;
if (typeof obj.con == "function") {
this._fun = obj.con;
} else {
this._con = obj.con;
}
this.__active();
var event = 'onclick';
switch (type) {
case 'click':
event = 'onclick';
break;
case 'over':
event = 'onmouseover';
break;
}
for (var i = 0, len = this._bar.length; i < len; i++) {
var a = this._bar[i];
a.index = i;
a[event] = function () {
chooseBar.__active(this.index);
}
}
}
};
/*测试用例*//*点击后显示隐藏对应div*//* chooseBar.click({bar: document.querySelectorAll("#bar li"), con: document.querySelectorAll("#con li")}); 点击触发事件*/
chooseBar.click({
bar: document.querySelectorAll(".menu li"), con: function (i) {
alert(i)
}
});
var ID = {
__valid: function (id) {
return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(id);
}, getBirthDate: function (cardId) {
if (!this.__valid(cardId)) return console.log("身份证不合法");
return cardId.substr(6, 4) + "-" + this.getBirthday(cardId);
}, getBirthday: function (cardId) {
if (!this.__valid(cardId)) return console.log("身份证不合法");
return cardId.substr(10, 2) + "-" + cardId.substr(12, 2);
}, getSex: function (cardId) {
if (!this.__valid(cardId)) return console.log("身份证不合法");
return parseInt(cardId.substr(16, 1)) % 2 == 1 ? "男" : "女";
}, getAge: function (cardId) {
if (!this.__valid(cardId)) return console.log("身份证不合法");
var age = new Date().getFullYear() - cardId.substr(6, 4);
new Date(new Date().getFullYear() + "-" + this.getBirthday(cardId)) > new Date() && age--;
return age;
}
};
/**复杂url?data=参数自动获取以及设置*/ var ud = {
get: function (data) {
return JSON.parse(hash.getQueryString(data || "data"));
}, set: function (data, keyName) {
return "?" + (keyName || "data") + "=" + encodeURIComponent(JSON.stringify(data));
},
};
/**该网页所在的域名目录必须是: 1、设置网页授权域名,否则无法获取openid(微信公众平台后台“右上角头像→功能设置”的配置选项中,修改授权回调域名。请注意,这里填写的是域名(是一个字符串),而不是URL) 2、设置JSAPI支付授权目录,否则无法唤起微信支付窗口(微信支付商户平台“产品中心→开发配置→支付配置→JSAPI支付授权目录”添加具体指向该页面所在域名目录)*/ var getOpenIdUrl = "http://192.168.1.108:9999/wechat/getAccessTokenAndOpenId";
/*获取openid*/
var createOrderUrl = "http://192.168.1.108:9999/wepay/createOrder";
/*创建微信预支付订单*/
var notifyUrl = "http://www.sg.com:9999/wepay/notifyUrl";
/*通知url必须为直接可访问的url,不能携带参数。示例:notify_url(https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_7&index=8)*/
/**微信支付JSAPI唤起支付窗口*/ var wePay = {
_api: createOrderUrl, _data: {}, __onBridgeReady: function () {
var d = this._data;
WeixinJSBridge.invoke('getBrandWCPayRequest', {appId: d.appId, timeStamp: d.timeStamp, nonceStr: d.nonceStr, package: d.package, signType: d.signType, paySign: d.paySign}, function (d) {
alert("微信返回信息:" + JSON.stringify(d, null, 4));
if (d.err_msg == "get_brand_wcpay_request:ok") {
alert("支付成功!");
/*显示支付成功结果页*/
location.replace("paySuccessResult.html?body=&price=&out_trade_no=" + d.out_trade_no + "&timeStamp=" + d.timeStamp);
} else if (d.err_msg == "get_brand_wcpay_request:cancel") {
alert("支付取消!");
history.go(-1);
} else if (d.err_msg == "get_brand_wcpay_request:fail") {
alert("支付失败!");
history.go(-1);
}
});
}, __showWePayDialog: function (data) {
this._data = data.data;
if (typeof WeixinJSBridge == "undefined") {
if (document.addEventListener) {
document.addEventListener('WeixinJSBridgeReady', this.__onBridgeReady, false);
} else if (document.attachEvent) {
document.attachEvent('WeixinJSBridgeReady', this.__onBridgeReady);
document.attachEvent('onWeixinJSBridgeReady', this.__onBridgeReady);
}
} else {
this.__onBridgeReady();
}
}, pay: function (obj) {
/**舒工自定义调用Ajax 2.0.2*/ $g.ajax({
post: {url: this._api, data: {body: obj.body, out_trade_no: obj.out_trade_no, total_fee: obj.total_fee, notify_url: obj.notify_url, openid: obj.openid}, noToken: true}, get: {
success: function (d) {
if (d.code == 200) {
wePay.__showWePayDialog(d);
} else {
alert(JSON.stringify(d, null, 4));
}
}, error: function (d) {
console.log("【报错】" + JSON.stringify(d, null, 4));
},
}
});
}
};
/*获取code-------------------------------------------------------------------------*/
var code = hash.getQueryString("code"), openId;
alert("CODE:" + code);
/*获取openid-------------------------------------------------------------------------*/
/**舒工自定义调用Ajax 2.0.2*/ $g.ajax({
post: {url: getOpenIdUrl, data: {code: code}, noToken: true}, get: {
success: function (d) {/* alert(JSON.stringify(d, null, 4));*/
openId = d.data.openid;
alert("openId:" + openId);
}, error: function (d) {
alert(JSON.stringify(d, null, 4));
},
}
});
/*唤起支付-------------------------------------------------------------------------*/
var obj = {body: "产品名称", out_trade_no: "SG_order_" + Number(new Date()), total_fee: 1, notify_url: notifyUrl, /* openid: "o07LNv8MhotwnZoWmDfx0oK5ZYik"*/};
document.querySelector("button").onclick = function () {
obj.openid = openId;
wePay.pay(obj);
}
/*-------------------------------------------------------------------------*/
var userAgent = {
_ua: navigator.userAgent, _ual: navigator.userAgent.toLocaleLowerCase(), /**判断是否为PC电脑端浏览器*/ isPC: function () {
var ua = this._ual;
return ua.indexOf("pad") == -1 && ua.indexOf("mobile") == -1;
}, /**判断是否为手机端*/ isPhone: function () {
var ua = this._ual;
return ua.indexOf("pad") == -1 && ua.indexOf("mobile") > -1;
}, /**判断是否为平板电脑*/ isPad: function () {
var ua = this._ua, isAndroid = /(?:Android)/.test(ua), isFireFox = /(?:Firefox)/.test(ua);
return /(?:iPad|PlayBook)/.test(ua) || (isAndroid && !/(?:Mobile)/.test(ua)) || (isFireFox && /(?:Tablet)/.test(ua));
}, /**判断是否是微信浏览器*/ isWeixinBrowser: function () {
return this._ual.indexOf("micromessenger") != -1;
}, /**监听是否为苹果电脑自带浏览器safari*/ safariBrowser: function (func) {
func || (func = function () {
alert("请不要使用safari这种低端浏览器,我唾弃你的品位!点击关闭,让我们一起安装高大上的谷歌浏览器吧,祝你早日富可敌国!么么哒~😊");
window.opener = null;
/*为了不出现提示框*/
window.close();
/*关闭窗口*/
window.open("http://shuzhiqiang.com/files/googlechrome.dmg");
});
var isSafari = /Safari/.test(this._ua) && !/Chrome/.test(this._ua);
if (isSafari) func();
}, /**移动端浏览器跳转*/ mobileBrowserRedirect: function (mobilePageOrFunc, webPageOrFunc) {
var ua = this._ual, ipad = ua.indexOf("ipad") > -1, iphone = ua.indexOf("iphone os") > -1, midp = ua.indexOf("midp") > -1, uc7 = ua.indexOf("rv:1.2.3.4") > -1, uc = ua.indexOf("ucweb") > -1, andriod = ua.indexOf("android") > -1,
ce = ua.indexOf("windows ce") > -1, wm = ua.indexOf("windows mobile") > -1, wx = ua.indexOf("micromessenger") > -1, isMobile = ipad || iphone || midp || uc7 || uc || andriod || ce || wm || wx;
if (isMobile) {
document.querySelector("html").style.display = "none";
typeof mobilePageOrFunc == "string" && location.replace(mobilePageOrFunc);
typeof mobilePageOrFunc == "function" && mobilePageOrFunc();
} else {
typeof webPageOrFunc == "string" && location.replace(webPageOrFunc);
typeof webPageOrFunc == "function" && webPageOrFunc();
}
return isMobile;
/*测试用例*/
/*mobileBrowserRedirect(function () {alert("该页面暂不支持移动端访问,请用电脑访问😊")})*/
}, /**判断是移动端浏览器*/ isMobilePhoneBrowser: function (mobilePhoneCallback, padCallback, otherMobileCallback) {
var ua = this._ua;
if (/AppleWebKit.*mobile/i.test(ua) || (/MIDP|SymbianOS|NOKIA|SAMSUNG|LG|NEC|TCL|Alcatel|BIRD|DBTEL|Dopod|PHILIPS|HAIER|LENOVO|MOT-|Nokia|SonyEricsson|SIE-|Amoi|ZTE/.test(ua))) {
if (location.href.indexOf("?mobile") < 0) {
try {
if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(ua)) {
mobilePhoneCallback ? mobilePhoneCallback() : location.replace("手机页面.html");
return true;
} else if (/iPad/i.test(ua)) {
padCallback ? padCallback() : location.replace("平板页面.html");
return true;
} else {
otherMobileCallback ? otherMobileCallback() : location.replace("其他移动端页面.html");
return true;
}
} catch (e) {
console.log(e);
}
}
}
return false;
}, /**判断是IOS系统*/ isIOS: function () {
var u = this._ua, app = navigator.appVersion;
var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
/*ios终端*/
return isIOS;
}, /**判断是Android系统*/ isAndroid: function () {
var u = this._ua, app = navigator.appVersion;
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1;
/*g*/
return isAndroid
},
}
var swiper = {
_swiper: null, _swiperScroll: null, __scrollTop: function () {
top.scrollTo(0, 0);
window.scrollTo(0, 0);
}, init: function (type, sel) {
this.__scrollTop();
type || (type = 0);
var effect = "slide";
/*默认为"slide"(位移切换),可设置为'slide'(普通切换、默认),"fade"(淡入)"cube"(方块)"coverflow"(3d流)"flip"(3d翻转)。*/
switch (type) {
case 0:
effect = "slide";
break;
case 1:
effect = "fade";
break;
case 2:
effect = "cube";
break;
case 3:
effect = "coverflow";
break;
case 4:
effect = "flip";
break;
case 5:
break;
default:
effect = "slide";
}
this._swiper = new Swiper(sel || '.swiper-container', {
autoplay: true,
speed: 500,
effect: effect,
loop: true,
grabCursor: true,
cubeEffect: {shadow: false, slideShadows: false, /*去掉coverflow下的背景阴影*/},
coverflowEffect: {rotate: 50, stretch: 300, depth: 300, modifier: 1, slideShadows: false, /*去掉coverflow下的背景阴影*/},
flipEffect: {slideShadows: false, /*去掉coverflow下的背景阴影*/},
pagination: {el: '.swiper-pagination',},
navigation: {nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev',},
});
}, initScroll: function (sel) {
this.__scrollTop();
this._swiperScroll = new Swiper(sel || '.swiper-scroll-container', {direction: 'vertical', slidesPerView: 'auto', freeMode: true, mousewheel: true, scrollbar: {el: '.swiper-scrollbar', hide: true, /*停止滚动后,滚动条默默地消失…*/},});
},
};
var countDown = {
/**倒计时(00:00:00)*/
timeout5hour:null,
fromTotalTime4Hour: function (fromTime, intervalCallback, nearEndCallback, endCallback) {
var h, m, s;
if (fromTime >= 0) {
h = Math.floor(fromTime / 3600), m = Math.floor(fromTime % 3600 / 60), s = Math.floor(fromTime % 60), intervalCallback && intervalCallback({
hours: h<10?'0'+h:h,
minutes: m<10?'0'+m:m,
seconds: s<10?'0'+s:s
}), nearEndCallback && (fromTime == 60) && nearEndCallback("还剩1分钟");
this.timeout5hour=setTimeout(function () {
countDown.fromTotalTime4Hour(--fromTime, intervalCallback, nearEndCallback, endCallback);
}, 1000);
} else {
endCallback && endCallback("时间到");
}
},
/**倒计时(00分00秒)*/
timeout:null,
fromTotalTime: function (fromTime, intervalCallback, nearEndCallback, endCallback) {
var m, s;
if (fromTime >= 0) {
m = Math.floor(fromTime / 60), s = Math.floor(fromTime % 60), intervalCallback && intervalCallback({minutes: m, seconds: s}), nearEndCallback && (fromTime == 60) && nearEndCallback("还剩1分钟");
this.timeout=setTimeout(function () {
countDown.fromTotalTime(--fromTime, intervalCallback, nearEndCallback, endCallback)
}, 1000);
} else {
endCallback && endCallback("时间到");
}
}, toDateTime: function (datetime, intervalCallback, nearEndCallback, endCallback) {
var difTime = new Date(datetime).getTime() - new Date().getTime();
var res, y, d, h, m, s, os = 1000;
if (difTime >= 0) {
y = Math.floor(difTime / os / 60 / 60 / 24 / 365), d = Math.floor(difTime / os / 60 / 60 / 24 % 365), h = Math.floor(difTime / os / 60 / 60 % 24), m = Math.floor(difTime / os / 60 % 60), s = Math.floor(difTime / os % 60), res = {
year: y,
day: d,
hour: h,
minutes: m,
seconds: s
}, nearEndCallback && (difTime == 60) && nearEndCallback("还剩1分钟");
} else {
endCallback && endCallback("时间到");
}
intervalCallback && intervalCallback(res);
setTimeout(function () {
countDown.toDateTime(datetime, intervalCallback, nearEndCallback, endCallback);
}, os);
}
};
/*测试用例1*/
countDown.fromTotalTime4Hour(2 * 60 * 60, function (res) {
countDownTimeDom.innerText =`${res.hours}:${res.minutes}:${res.seconds}`;
}, function (e) {
layer.msg("还剩一分钟就要自动交卷了,注意检查是否还有遗漏的试题!");
/*还剩1分钟!*/
}, function (e) {
layer.alert("考试结束,已为您自动提交答题卡", {resize: false, title: "提示", btn: ["知道了"], btnAlign: "c", icon: 0});
/*时间到!*/
});
/*测试用例2*/
countDown.fromTotalTime(1 * 60, function (res) {
document.querySelector("body").innerText = res.minutes + "分" + res.seconds + "秒";
}, function (e) {
alert(e);
/*还剩1分钟!*/
}, function (e) {
alert(e);
/*时间到!*/
})
countDown.toDateTime("2019-10-24 00:00:00", function (res) {
document.querySelector("body").innerText = res.year + "年" + res.day + "天" + res.hour + "时" + res.minutes + "分" + res.seconds + "秒";
})
//模拟双击事件----------------------------------------------------------------
function doubleClick(sel, func) {
var timeStamp = null;
document.querySelector(sel).onclick = function (e) {
if (timeStamp && e.timeStamp - timeStamp < 300) {/*间隔低于300毫秒连续单击认为是双击*/
func && func();
} else {
timeStamp = e.timeStamp
}
};
}
/*测试用例*/
doubleClick("button", function () {
alert("你刚刚双击了按钮");
})
//原生的双击----------------------------------------------------------------
dom.ondblclick=function(){
//双击事件
}
var select = {
/**获取下拉框的value和text*/ get: function (sel) {
typeof sel == "string" && (sel = document.querySelector(sel));
sel = sel.options[sel.selectedIndex];
return {value: sel.value, text: sel.text};
}, /**下拉框html初始化*/ init: function (sel, dataArray, index) {
typeof sel == "string" && (sel = document.querySelector(sel));
var html = "";
for (var i in dataArray) {
var data = dataArray[i];
html += "<option value='" + data.id + "'" + (data.id == index ? "selected='selected'" : '') + ">" + data.value + "</option>";
}
sel.innerHTML = html;
return html;
}
};
/**淡入淡出,需要引入jquery*/
function setTimeFadeInOut(sel, time, speed) {
typeof sel == "string" && (sel = document.querySelector(sel));
sel = $(sel);
time || (time = 3);
speed || (speed = "fast");
sel.stop().fadeIn(speed);
setTimeout(function () {
sel.stop().fadeOut(speed);
}, time * 1000);
}
/*测试用例*/
setTimeFadeInOut("sel", 3, "fast");
/**间隔屏蔽功能*/
function setTimePointerEvents(sel, time) {
sel = typeof sel == "string" ? document.querySelector(sel) : (sel instanceof jQuery ? sel[0] : sel);
time || (time = 1);
sel.style.pointerEvents = "none";
setTimeout(function () {
sel.style.pointerEvents = "auto";
}, time * 1000)
}
/*测试用例*/
setTimePointerEvents("sel", 3);
var img = {
getSize: function (imgUrl, callback) {
/**设置div为图片实时预加载宽度、高度*/ imgUrl = imgUrl + "?" + Number(new Date());
var img = new Image();
img.src = imgUrl;
/* 定时执行获取宽高*/
var set = setInterval(function () {
var obj = {width: img.width, height: img.height};
if (obj.width > 0 && obj.height > 0) {
clearInterval(set);
callback && callback(obj);
}
}, 1);
}, setRealSize: function (sel, attr, imgUrl) {
var DIV = document.querySelector(sel)
/**设置div为图片真实宽度、高度*/ imgUrl = imgUrl + "?" + Number(new Date());
var img = new Image();
img.src = imgUrl;
img.onload = function () {
(attr == "width" || attr == "size") && (DIV.style.width = this.width + "px");
(attr == "height" || attr == "size") && (DIV.style.height = this.height + "px");
};
}, setRealtimeSize: function (sel, attr, imgUrl) {
var DIV = document.querySelector(sel)
/**设置div为图片实时预加载宽度、高度*/ imgUrl = imgUrl + "?" + Number(new Date());
var img = new Image();
img.src = imgUrl;
/* 定时执行获取宽高*/
var set = setInterval(function () {
var iw = img.width;
var ih = img.height;
if (iw > 0 && ih > 0) {
clearInterval(set);
(attr == "width" || attr == "size") && (DIV.style.width = iw + "px");
(attr == "height" || attr == "size") && (DIV.style.height = ih + "px");
}
}, 1);
}
};
/*测试用例*/
img.setRealSize("div", "size", "https://img.zcool.cn/community/019a455b3e9007a80120b959405c57.jpg");
img.setRealtimeSize("div", "size", "https://img.zcool.cn/community/019a455b3e9007a80120b959405c57.jpg");
img.getSize("https://www.baidu.com/img/bd_logo1.png", function (obj) {
console.log(obj);
/*获取百度图片的宽度高度*/
})
var replace = {
/**替换字符串里面所有指定字符*/ replaceWords: function (str, replacedWord, replaceWord) {
replacedWord || (replacedWord = " ");
replaceWord || (replaceWord = "");
return str.replace(new RegExp(replacedWord, "g"), replaceWord);
}, /**去掉最后一个字符串*/ removeLastChar: function (s) {
s = s.toString();
return s.substr(0, s.length - 1);
}, /**去掉字符串中的特殊字符*/ removeSpecialCharacter: function (s) {/* 去掉转义字符*/
s = s.replace(/[\'\"\\\/\b\f\n\r\t]/g, '');
/* 去掉特殊字符*/
s = s.replace(/[\@\#\$\%\^\&\*\(\)\{\}\:\"\L\<\>\?\[\]]/g, '');
return s;
}
};
/*测试用例*/
alert(replace.replaceWords("有天我睡醒看到我的身边没有你", "我", "你"))
var ip = {
isLocal: function () {
var lh = top.location.href;
return (lh.indexOf("localhost") > -1 || lh.indexOf("127.0.0.1") > -1);
}, localIP: function (callback) {
var ip = {}, R = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection, M = {optional: [{RtpDataChannels: true}]}, S = {iceServers: [{urls: "stun:stun.services.mozilla.com"}]}, f = function () {
};
if (!R) {
var win = iframe.contentWindow, R = win.RTCPeerConnection || win.mozRTCPeerConnection || win.webkitRTCPeerConnection;
}
var P = new R(S, M);
function h(c) {
var r = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/;
var a = r.exec(c)[1];
if (ip[a] === undefined) {
callback(a);
}
ip[a] = true;
}
P.onicecandidate = function (i) {
if (i.candidate) h(i.candidate.candidate);
};
P.createDataChannel("");
P.createOffer(function (r) {
P.setLocalDescription(r, f, f);
}, f);
setTimeout(function () {
var ls = P.localDescription.sdp.split('\n');
ls.forEach(function (l) {
if (l.indexOf('a=candidate:') === 0) h(l);
});
}, 1);
}
};
/*测试用例*/
ip.localIP(function (ip) {
alert('您本机的局域网(内网)IP是 ' + ip);
});
/**设置快捷键*/onkeyup = function (e) {
var k = e.keyCode || e.which || e.charCode, ck = e.ctrlKey || e.metaKey, ak = e.altKey, sk = e.shiftKey;
/**独立键*/
if (k == 13) {/*按下回车键Enter↩的时候执行*/
}
if (k == 27) {/*按下退出键Esc的时候执行*/
}
if (k == 36) {/*执行Home*/
}
if (k == 35) {/*执行End*/
}
if (k == 48 || k == 96) {/*执行0、Num0*/
}
if (k == 49 || k == 97) {/*执行1、Num1*/
}
if (k == 37 || k == 38 || k == 27 || k == 8) { /*按下 ← ↑ Esc <BACKSAPCE 的时候执行*/
}
if (k == 33 || k == 37 || k == 38 || k == 100 || k == 104 || e.keyCode === 80) {/*执行Page Up、←、↑、Num4(←)、Num8(↑)、P*/
}
if (k == 34 || k == 39 || k == 40 || k == 102 || k == 98 || e.keyCode === 78) {/*执行Page Down、→、↓、Num2(→)、Num6(↓)、N*/
}
/**组合键*/
if (ck && k == 13) {/*Ctrl+Enter*/
alert('submit');
}
if (sk && k == 13) {/*Shift+Enter*/
alert('change line');
}
if (ck && ak && sk && k == 83) {/*Ctrl+Alt+Shift+S*/
alert('导出web图片');
}
}
/*屏蔽拷贝图片________________________________________________*/
function DontCopyMyImage() { /*知识产权保护措施:禁止右键查看、禁止复制文本、禁止使用快捷键截图(很遗憾无法禁用Print Screen屏幕截图按钮)*/
var HTMLDOM = document.querySelector("html");
/*屏蔽拖拽保存图片*/
window.ondragstart = window.ontouchmove = document.ondragstart = document.ontouchmove = function (e) {
e.preventDefault();
return false;
};
/*防止用键盘截屏快捷键截图*/
var hideBodyIntervalID1, hideBodyIntervalID2;
/*老子设置两个毫秒级的刷新事件干死你了!*/
window.oncontextmenu = document.oncontextmenu = new Function("event.returnValue=false;");
window.onselectstart = document.onselectstart = new Function("event.returnValue=false;");
window.oncopy = document.oncopy = new Function("event.returnValue=false;");
window.onkeydown = document.onkeydown = function (e) {
var currKey = e.keyCode || e.which || e.charCode;
var isKeyF1toF12 = currKey > 111 && currKey < 124 && currKey != 116;
var isPrintOrInsert = currKey == 42 || currKey == 44 || currKey == 45 || currKey == 145;
var isCombinatorialKey = event.shiftKey || event.ctrlKey || event.altKey || e.shiftKey || e.ctrlKey || e.altKey;
if (isKeyF1toF12 || isCombinatorialKey || isPrintOrInsert) {
hideBody();
CloseWebPage();
/* window.open("javascript: alert('朋友!您是想要截屏还是查看源代码呢?\\r\\n如果没办法拷贝截图和代码可以\\r\\n联系舒工");*/
}
};
window.onblur = document.onblur = hideBody;
window.onfocus = document.onfocus = showBody;
function hideBody() {
hideBodyIntervalFunc();
hideBodyIntervalFunc();
hideBodyIntervalID1 = setInterval(hideBodyIntervalFunc, 1);
hideBodyIntervalID2 = setInterval(hideBodyIntervalFunc, 1);
}
function hideBodyIntervalFunc() {
HTMLDOM.style.opacity = "0";
HTMLDOM.style.display = "none";
HTMLDOM.style.visibility = "hidden";
HTMLDOM.style.opacity = "0";
HTMLDOM.style.display = "none";
HTMLDOM.style.visibility = "hidden";
HTMLDOM.style.opacity = "0";
HTMLDOM.style.display = "none";
HTMLDOM.style.visibility = "hidden";
HTMLDOM.style.opacity = "0";
HTMLDOM.style.display = "none";
HTMLDOM.style.visibility = "hidden";
HTMLDOM.style.opacity = "0";
HTMLDOM.style.display = "none";
HTMLDOM.style.visibility = "hidden";
HTMLDOM.style.opacity = "0";
HTMLDOM.style.display = "none";
HTMLDOM.style.visibility = "hidden";
HTMLDOM.style.opacity = "0";
HTMLDOM.style.display = "none";
HTMLDOM.style.visibility = "hidden";
HTMLDOM.style.opacity = "0";
HTMLDOM.style.display = "none";
HTMLDOM.style.visibility = "hidden";
HTMLDOM.style.opacity = "0";
HTMLDOM.style.display = "none";
HTMLDOM.style.visibility = "hidden";
HTMLDOM.style.opacity = "0";
HTMLDOM.style.display = "none";
HTMLDOM.style.visibility = "hidden";
HTMLDOM.style.opacity = "0";
HTMLDOM.style.display = "none";
HTMLDOM.style.visibility = "hidden";
HTMLDOM.style.opacity = "0";
}
function showBody() {
clearInterval(hideBodyIntervalID1);
clearInterval(hideBodyIntervalID2);
HTMLDOM.style.display = "block";
HTMLDOM.style.visibility = "visible";
HTMLDOM.style.opacity = "1";
}
/*强制关闭不提示*/
function CloseWebPage() {
if (navigator.userAgent.indexOf("MSIE") > 0) {
if (navigator.userAgent.indexOf("MSIE 6.0") > 0) {
window.opener = null;
window.close();
} else {
window.open('', '_top');
top.close();
}
} else if (navigator.userAgent.indexOf("Firefox") > 0) {
window.top.location.replace("about:blank")
} else {
window.opener = null;
window.open('', '_self', '');
window.close();
}
}
}
/*________________________END________________________ 屏蔽拷贝图片________________________*/
/**将form表单各个参数组合为字符串形式*/
/**获取指定form中的所有的<input>对象*/
function getElements(formId) {
var form = document.getElementById(formId);
var elements = [];
var tagElements = form.getElementsByTagName('input');
for (var j = 0; j < tagElements.length; j++) {
elements.push(tagElements[j]);
}
var tagElements = form.getElementsByTagName('select');
for (var j = 0; j < tagElements.length; j++) {
elements.push(tagElements[j]);
}
var tagElements = form.getElementsByTagName('textarea');
for (var j = 0; j < tagElements.length; j++) {
elements.push(tagElements[j]);
}
return elements;
}
/**组合URL*/function serializeElement(element) {
var method = element.tagName.toLocaleLowerCase();
var parameter;
if (method == 'select') {
parameter = [element.name, element.value];
}
switch (element.type.toLocaleLowerCase()) {
case 'submit':
case 'hidden':
case 'password':
case 'text':
case 'date':
case 'textarea':
parameter = [element.name, element.value];
break;
case 'checkbox':
case 'radio':
if (element.checked) {
parameter = [element.name, element.value];
}
break;
}
if (parameter) {
var key = encodeURIComponent(parameter[0]);
if (key.length == 0) return;
if (parameter[1].constructor != Array) parameter[1] = [parameter[1]];
var values = parameter[1];
var results = [];
for (var i = 0; i < values.length; i++) {
results.push(key + '=' + encodeURIComponent(values[i]));
}
return results.join('&');
}
}
/**调用方法*/
function formToConnectionParameters(formId) {
var elements = getElements(formId);
var queryComponents = [];
for (var i = 0; i < elements.length; i++) {
var queryComponent = serializeElement(elements[i]);
if (queryComponent) {
queryComponents.push(queryComponent);
}
}
return queryComponents.join('&');
}
/**form表单是否有未填写内容*/
function formHasNull(formId) {
var form = document.getElementById(formId);
for (var i = 0; i < form.elements.length; i++) {
var feled = form.elements[i];
switch (feled.type) {
case undefined:
case 'button':
case 'file':
case 'reset':
case 'submit':
break;
case 'checkbox':
case 'radio':
if (!feled.checked) {
return true;
break;
}
default:
if (feled.value.replace(/\ |\ /g, "") == "") {
return true;
break;
}
}
}
return false;
}
<!--路由-->
<script src="http://apps.bdimg.com/libs/angular.js/1.2.16/angular.min.js"></script>
<script src="http://cdn.staticfile.org/angular-ui-router/0.2.11/angular-ui-router.min.js"></script>
<script>
var myApp = angular.module("myApp", ["ui.router"]);
myApp.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.when("", "/home").otherwise("/404");
$stateProvider
.state("home", {url: "/home", template: "<h1>首页</h1>"})//可以直接写html
.state("about", {url: "/about", templateUrl: "about.html"})//也可以传递外部html,该html里面无需写html、body、head标签
.state("contacts", {
url: "/contacts", template: "<h1>联系我们</h1>"//可以通过resolve预加载依赖的外部js
/**,
resolve: {
deps: ['uiLoad', function (uiLoad) {
return uiLoad.load(['js/name1.js', 'js/name2.js']);
//需要依赖ui-load.js
}]
}*/
});
});
</script>
<div ng-app="myApp">
<a ui-sref="home">home</a> <a ui-sref="about">about</a> <a ui-sref="contacts">contacts</a>
<div ui-view></div>
</div>
$g.$utils.screen = {
/**实现F11全屏效果*/
fullScreen() {
var docElm = document.documentElement;
/*W3C*/
if (docElm.requestFullscreen) {
docElm.requestFullscreen();
}/*FireFox */ else if (docElm.mozRequestFullScreen) {
docElm.mozRequestFullScreen();
}/*Chrome等 */ else if (docElm.webkitRequestFullScreen) {
docElm.webkitRequestFullScreen();
}/*IE11*/ else if (docElm.msRequestFullscreen) {
docElm.msRequestFullscreen();
}
},
/**退出F11全屏*/
exitFullScreen() {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitCancelFullScreen) {
document.webkitCancelFullScreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
}
},
/**判断全屏模式是否是可用*/
isFullscreenEnabled() {
return document.fullscreenEnabled || document.mozFullScreenEnabled || document.webkitFullscreenEnabled || document.msFullscreenEnabled || false;
},
/**判断整个页面被一个标签铺满*/
isFullscreenForNoScroll() {
var explorer = window.navigator.userAgent.toLowerCase();
if (explorer.indexOf("chrome") > -1) {/*webkit*/
return (document.body.scrollHeight === window.screen.height && document.body.scrollWidth === window.screen.width);
} else {/*IE 9+ fireFox*/
return (window.outerHeight === window.screen.height && window.outerWidth === window.screen.width);
}
},
/**判断是否全屏*/
isFullScreen() {
return document.fullscreenElement || document.msFullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement ? true : false;
},
/**实现局部div、dom元素全屏*/
fullScreenForDOM(sel) {
typeof sel == "string" && (sel = document.querySelector(sel));
/**el是具体的dom元素*/var rfs = sel.requestFullScreen || sel.webkitRequestFullScreen || sel.mozRequestFullScreen || sel.msRequestFullScreen, wscript;
if (typeof rfs != "undefined" && rfs) {
rfs.call(sel);
return;
}
if (typeof window.ActiveXObject != "undefined") {
wscript = new ActiveXObject("WScript.Shell");
if (wscript) {
wscript.SendKeys("{F11}");
}
}
},
exitFullScreenForDOM(sel) {
typeof sel == "string" && (sel = document.querySelector(sel));
/**el是具体的dom元素*/var el = document, cfs = sel.cancelFullScreen || sel.webkitCancelFullScreen || sel.mozCancelFullScreen || sel.exitFullScreen, wscript;
if (typeof cfs != "undefined" && cfs) {
cfs.call(el);
return;
}
if (typeof window.ActiveXObject != "undefined") {
wscript = new ActiveXObject("WScript.Shell");
if (wscript != null) {
wscript.SendKeys("{F11}");
}
}
}
};
/**递归循环方法(可设置delay延时递归)*/
function dg(arr, i, delay) {
i || (i = 0), delay || (delay = 0);
var a = arr[i];
//这里写代码
i++, setTimeout(function () {
i < arr.length && dg(arr, i, delay);
}, delay)
}
var arr =
dg(arr);
//点击全局页面其他部分→隐藏指定DOM
document.onmousedown = function(e) {
e.path.indexOf(指定DOM) == -1 && 隐藏方法();
};
//顶部导航条(菜单)随着滚动条隐藏:1、滚动条往下隐藏导航条;2、滚动条往上显示导航条
var initScroll = function () {
var nav = document.querySelector("导航条"), nh = nav.offsetHeight, beforeScrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0, html = document.querySelector("html");
onscroll = function () {
var afterScrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0, hy = html.getBoundingClientRect().y;
if (afterScrollTop > beforeScrollTop && hy < -nh) {
nav.style.marginTop = -1 * nh + "px";
hy < -window.innerHeight && 显示返回顶部按钮();
} else {
nav.style.marginTop = 0;
隐藏返回顶部按钮();
}
beforeScrollTop = afterScrollTop;
}
};
initScroll();
/*获取子DOM元素在父元素里面的索引位置(是第几个元素)*/
function getNodeListIndex(childNode) {
return childNode && childNode.parentNode ? Array.prototype.indexOf.call(childNode.parentNode.children, childNode) : null;
}
<!-- 自定义虚线/实线样式 -->
<hr class="sg-hr" />
<style>
.sg-hr,hr {
border: none;
height: 0;
width: 100%;
border-top: 2px solid #f3f3f3;
margin: 20px 0 10px 0;
}
</style>
<!--原生表格纵向滚动条-->
<style>
thead, tbody {
display: block;
}
tbody {
overflow-y: auto;
max-height: 100px; /*正文表格最大高度*/
}
</style>
<table>
<thead>
<tr>
<td>表头1</td>
<td>表头2</td>
</tr>
</thead>
<tbody>
<tr>
<td>内容1</td>
<td>内容2</td>
</tr>
<tr>
<td>内容1</td>
<td>内容2</td>
</tr>
<tr>
<td>内容1</td>
<td>内容2</td>
</tr>
<tr>
<td>内容1</td>
<td>内容2</td>
</tr>
<tr>
<td>内容1</td>
<td>内容2</td>
</tr>
</tbody>
</table>
/*任意字符串转为像素单位*/
var getPx = function (num) {
num || (num = 0), num = num.toString().toLowerCase();
return num + ((num.indexOf('px') > -1 || num.indexOf('%') > -1) ? '' : 'px');
}
/*获取鼠标移动方向*/
function getMouseDirection(sel) {
var wrap = document.querySelector(sel);
var hoverDir = function (e) {
var w = wrap.offsetWidth, h = wrap.offsetHeight, x = (e.clientX - wrap.offsetLeft - (w / 2)) * (w > h ? (h / w) : 1), y = (e.clientY - wrap.offsetTop - (h / 2)) * (h > w ? (w / h) : 1),
direction = Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180) / 90) + 3) % 4;
/* 上(0) 右(1) 下(2) 左(3)*/
console.log(direction);
}
if (window.addEventListener) {
wrap.addEventListener('mousemove', hoverDir, false);
} else if (window.attachEvent) {
wrap.attachEvent('mousemove', hoverDir);
}
}
getMouseDirection('body');
/*DOM类型判断*/
var isDOM = (typeof HTMLElement === 'object') ? function (obj) {
return obj instanceof HTMLElement;
} : function (obj) {
return obj && typeof obj === 'object' && obj.nodeType === 1 && typeof obj.nodeName === 'string';
}
/*获取DOM*/
var __getDOM = function (dom) {
return (typeof dom == 'string' ? document.querySelector(dom) : dom) || null;
}
//自由化传参【可以传入数组、离散的独立参数】
var __getFreeParams = function (args) {
var ra = [], arr = Array.isArray(args) ? args : arguments;
for (var i = 0, len = arr.length; i < len; i++) {
var a = arr[i];
a != undefined && ra.push(a);
}
return ra;
}
console.log(__getFreeParams(1, 2, 3, 4));
/*监听DIV内容发生变化*/
function addChangeListener(sel, changeEvent) {
document.querySelector(sel).addEventListener('DOMNodeInserted', function () {
changeEvent(this.innerHTML);
});
};
//在DOM开头加渲染
function insertBefore(sel, html) {
document.querySelector(sel).insertAdjacentHTML("afterbegin", html);
}
/*js实现jquery的append方法*/
//在DOM结尾追加渲染
function append(sel, html) {
document.querySelector(sel).insertAdjacentHTML("beforeend", html);
}
dom.scrollIntoView({behavior: "smooth", block: "nearest", inline: "nearest"});//缓慢滚动
/**
【behavior 可选】
定义动画过渡效果, "auto", "instant", 或 "smooth" 之一。默认为 "auto"。
【block 可选】
定义垂直方向的对齐, "start", "center", "end", 或 "nearest"之一。默认为 "start"。
【inline 可选】
定义水平方向的对齐, "start", "center", "end", 或 "nearest"之一。默认为 "nearest"。
*/
$('html').stop().animate({scrollTop: 滚动顶部位置}, 'fast', function () {console.log('滚动结束');});
//获取伪元素的样式
var getPseudoElementStyle = function (sel, pseudo, propertyName) {
return window.getComputedStyle(document.querySelector(sel), ':' + (pseudo || 'before')).getPropertyValue(propertyName || 'display');
};
console.log(getPseudoElementStyle('h1', 'after', 'content'));//测试
/*全站变成灰色(去色)*/
* {
filter: grayscale(100%);
-webkit-filter: grayscale(100%);
-moz-filter: grayscale(100%);
-ms-filter: grayscale(100%);
-o-filter: grayscale(100%);
filter: progid:DXImageTransform.Microsoft.BasicImage(grayscale=1);
-webkit-filter: grayscale(1);
}
&::after {
/* 向下的直角三角形箭头 */
content: "";
position: absolute;
top: 0px;
right: 0px;
width: 0;
height: 0;
border: 5px solid transparent;
border-top-color: red;
}
&::after {
/* 向右的直角三角形箭头 */`
content: "";
position: absolute;
top: 0px;
right: 0px;
width: 0;
height: 0;
border: 5px solid transparent;
border-left-color: red;
}
//Vue在新窗口弹出单页面
const { href } = this.$router.resolve({
path: "/singleNewsDetail",
query: { item: this.item, id: this.id }
});
window.open(href, "_blank");
//Vue节点绑定事件获取当前元素,并修改其样式
@click="$event.srcElement.style.display='none'"
// 当前点击的元素
$event.target;//等同于$event.srcElement
// 绑定事件的元素
$event.currentTarget;
// (target与currentTarget的区别主要体现在使用事件委托时,发生事件委托时,点击的元素与绑定事件的元素非同一元素,反之不发生事件委托时,两者相同,是同一元素)
// 获得绑定事件元素的前一个节点信息(包含元素节点、属性节点、文本节点、注释节点)
$event.currentTarget.previousSibling;
// 获得绑定事件元素的前一个元素节点(只包含元素节点,只有html内容)
$event.currentTarget.previousElementSibling;
// 下一个元素信息获取使用 nextSibling、nextElementSibling
// 获得绑定事件元素的父节点信息
$event.currentTarget.parentNode;
// 获得绑定事件元素的父级元素
$event.currentTarget.parentElement;
// 获得绑定事件元素的第一个子节点信息
$event.currentTarget.firstChild;
// 获得绑定事件元素的第一个子元素
$event.currentTarget.firstElementChild;
// 获得绑定事件元素中id为ceshi的元素集合
$event.currentTarget.getElementById("ceshi");
// 获得绑定事件元素中class为ceshi的元素集合
$event.currentTarget.getElementsByClassName("ceshi");
// 获得绑定事件元素的的内容(类似jquery的text())
$event.currentTarget.textContent;
// 获得绑定事件元素的的内容(类似jquery的html())
$event.currentTarget.innerHTML;
// 获得绑定事件元素的ceshi属性(类似jquery的attr('ceshi'))
$event.currentTarget.getAttributeNode("ceshi");
// 点击删除当前元素
$event.currentTarget.parentElement.removeChild(event.currentTarget);
// 点击删除当前元素的父级元素
$event.currentTarget.parentElement.parentElement.removeChild(event.currentTarget.parentElement);
/* 用白色渐变遮罩隐藏未显示完的文章部分 */
&::after {
content: "";
position: absolute;
left: 0;
bottom: 0;
width: 100%;
height: 100px;
/*从上往下渐变背景*/
background: -webkit-linear-gradient(
transparent,
white
); /* Safari 5.1 - 6.0 */
background: -o-linear-gradient(
transparent,
white
); /* Opera 11.1 - 12.0 */
background: -moz-linear-gradient(
transparent,
white
); /* Firefox 3.6 - 15 */
background: linear-gradient(
transparent,
white
); /* 标准的语法(必须放在最后) */
}
<!--Vue绑定html标签背景、样式-->
:style="{backgroundImage:'url('+item.bgUrl+')'}"
<!--根据索引值左右滑动-->
:style="{marginLeft:-100*currentIndex+'px'}"
单行省略号 {
/*单行省略号*/
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
多行省略号 {
/*多行省略号*/
overflow: hidden;
word-break: break-all;/*单词分割换行*/
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 行数(默认3);
height: 高度px;
}
/*js代码添加省略号*/
function addEllipsis(text, maxLength=10, suffix="…") {
text=text.toString();
return text.length > maxLength ? text.substr(0, maxLength - 1) + suffix : text;
}
//判断文本内容是否超出了外层DIV的高度、宽度,此时出现了纵向、横向滚动条(如果用了overflow: hidden;则不会出现滚动条)
if (DOM.scrollHeight > DOM.clientHeight) {
//设置paddingRight='10px'
//设置对应的移入Tip完整内容提示框(通常和CSS{display: -webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: 3;overflow: hidden;height:}高度px;多行省略号搭配使用)
}
if (DOM.scrollWidth > DOM.clientWidth) {
//设置对应的移入Tip完整内容提示框(通常和CSS{overflow: hidden;white-space: nowrap;text-overflow: ellipsis;}多行省略号搭配使用)
}
//递归把不同层级深度的数组元素转换为扁平化同一个层级的数组
function p(a, b = []) {Array.isArray(a) ? a.forEach(function (c) {p(c, b);}) : b.push(a);return b;}
console.log(p([1, [2, [3, 4], 5], 6]));
/*屏蔽移动端滑动、PC端滑动鼠标滚轮事件*/
function disableTouchmoveAndMouseWheel(sel, bool) { /*bool:false禁止,true解除禁止*/
sel = typeof sel == "string" ? document.querySelectorAll(sel) : [sel];
bool = Boolean(bool);
var arr = sel;
for (var i = 0, len = arr.length; i < len; i++) {
var a = arr[i];
a.ontouchmove = a.onmousewheel = function (e) {
bool || e.preventDefault && e.preventDefault();
e.returnValue = bool;
bool || e.stopPropagation && e.stopPropagation();
return bool;
}
}
}
<body
alt = "屏蔽右键"
oncontextmenu = "return false"
ondragstart = "return false"
onselectstart = "return false"
></body>
<!--循环自动播放背景音乐、隐藏播放器-->
<audio controls="controls" autoplay loop hidden>
<source src="sound/bg.mp3" type="audio/mpeg"/>
</audio>
<!--视频播放器-->
<video id="video"
src="video/1.mp4"
poster="img/video-default-cover.jpg"
controls
controlsList="nodownload"
autoplay
loop
width="100%"
height="100%"
>您的浏览器版本太陈旧了,赶紧去官网升级吧!</video>
/*禁用浏览器返回按钮、禁用浏览器回退按钮*/
function forbiddenBack() {
history.pushState(null, null, document.URL);//用当前页面网址覆盖最近的历史记录
window.addEventListener("popstate", function (e) {
history.pushState(null, null, document.URL);
}, false);
}
forbiddenBack();
//获取本地国家语言、语种类别
var lang = navigator.userLanguage||navigator.language;//常规浏览器或者IE本地化语言
lang = lang.toLowerCase().substr(0,2);//截取前两位支付
console.log(lang);
/*获取当前页面的最高层级*/
var getMaxZIndex = () => {
var arr = [...document.all].map(e => +window.getComputedStyle(e).zIndex || 0);
return arr.length ? Math.max(...arr) : 0;
};
/*模糊*/filter: blur(5px);
<!--富文本编辑器【舒工强烈推荐的编辑器】(帮助文档请登录www.wangeditor.com)-->
<!--SGeditor-->
<div class="SGeditor"><p>请在此处输入描述内容…</p></div>
<!--END SGeditor-->
<!--SGeditor-->
<script src="https://unpkg.com/wangeditor@3.1.1/release/wangEditor.min.js"></script>
<!--END SGeditor-->
<script type="text/javascript">var E = window.wangEditor;
var SGeditor = new E(".SGeditor");
SGeditor.customConfig.uploadImgServer = "/SGeditor-upload-img";
SGeditor.customConfig.uploadImgHooks = {
customInsert: function (insertImg, result, editor) {
console.log(JSON.stringify(result));
insertImg(result.data[0]);
}
};
/*SGeditor.customConfig.uploadImgParams = { a: 123, b: 'vvv' }, SGeditor.customConfig.uploadImgParamsWithUrl = true;*/
SGeditor.create();
</script>
/*自定义原生添加ClassName,模仿JQuery addClass() 方法*/
var Class = {
__convertDOM: function (sel) {
typeof sel == "string" && (sel = document.querySelector(sel));
return sel;
}, has: function (sel, cls) {
sel = this.__convertDOM(sel);
return sel.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
}, add: function (sel, cls) {
sel = this.__convertDOM(sel);
if (!Class.has(sel, cls)) sel.className += " " + cls;
}, remove: function (sel, cls) {
sel = this.__convertDOM(sel);
if (Class.has(sel, cls)) {
var reg = new RegExp(cls, "g");
sel.className = sel.className.replace(reg, "");
}
}, /*切换className*/ toggle: function (sel, cls) {
sel = this.__convertDOM(sel);
if (Class.has(sel, cls)) {
Class.remove(sel, cls);
} else {
Class.add(sel, cls);
}
}
};
/*测试用例*/
Class.toggle("body", "testClass");
/*scss循环*/
@for $i from 1 through length($数组) {
$color: nth($数组, $i);
&:nth-of-type(#{$i}) {
color: $color;
&:hover {
color: white;
}
}
}
/*图片填充文字背景*/
height: auto;
width: auto;
background: url(bg.png) no-repeat left center;
background-origin: border-box;
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
/*fillcolor是Webkit内核私有属性哦 */
/*渐变文字(仅谷歌内核浏览器支持)*/
background: -webkit-linear-gradient(white, black);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
<!- vue for循环 ->
v-for="(item,$index) in items"
:key="$index"
:hover="hoverIndex==$index"
:current="currentIndex==$index"
@mouseover="hoverIndex=$index,autoPlay=false"
@mouseout="hoverIndex=null,autoPlay=localAutoPlay"
@click="currentIndex=$index"
v-html="item.label"
<!- angular for循环 ->
<li
ng-repeat="item in items track by $index"
ng-click="
ng-bind-html="item"
>
{{item}}
</li>
// angularJS 用$loaction获取window.location信息
// open http://host.com/base/index.html#!/a
$location.absUrl() == 'http://host.com/base/index.html#!/a';
$location.path() == '/a';
$location.path('/foo');
$location.absUrl() == 'http://host.com/base/index.html#!/foo';
$location.search() == {};//search没东东的时候,返回空对象
$location.search({a: 'b', c: true});
$location.absUrl() == 'http://host.com/base/index.html#!/foo?a=b&c';
$location.path('/new').search('x=y');//可以用字符串的方式更改search,每次设置search,都会覆盖之前的search
$location.absUrl() == 'http://host.com/base/index.html#!/new?x=y';
/*强制关闭不提示*/
function CloseWebPage() {
window.location.replace("about:blank");
window.opener = null;
window.open('', '_self');
window.close();
}
var space = {
/*去掉字符串前后空格*/trimSpace: function (str) {
str || (str = "");
return str.replace(/(^\s*)|(\s*$)/g, "");
}, /*去掉字符串中所有空格(包括中间空格)*/trimAllSpace: function (str) {
str || (str = "");
return str.replace(/\s+/g, "");
}, /*去掉所有全角半角空格*/ trimAllWholeCornerSpace: function (str) {
str || (str = "");
return str.replace(/\ |\ /g, "");
}, /*去掉所有全角半角 空格*/ trimAllWholeCornerCodeSpace: function (str) {
str || (str = "");
return this.trimAllWholeCornerSpace(str).replace(/ /g, "");
}
};
/*转换为废代码文本(转换文本中的?<、>符号)*/
var replaceLTandGT = function (s) {
if (s == null || s == undefined) return "";
return s.toString().replace(/</g, "<").replace(/>/g, ">");
};
/*边框虚线滚动动画特效*/
.border-animate {
background: linear-gradient(90deg, gray 60%, transparent 60%) repeat-x left top/10px 1px,
linear-gradient(0deg, gray 60%, transparent 60%) repeat-y right top/1px 10px,
linear-gradient(90deg, gray 60%, transparent 60%) repeat-x right bottom/10px 1px,
linear-gradient(0deg, gray 60%, transparent 60%) repeat-y left bottom/1px 10px;
animation: border-animate .382s infinite linear;
}
@keyframes border-animate {
0% {
background-position: left top, right top, right bottom, left bottom;
}
100% {
background-position: left 10px top, right top 10px, right 10px bottom, left bottom 10px;
}
}
var random = {
/**获取两个数之间的随机小数(fixed是有效数字位数)*/
getDecimal(a, b, fixed) {
var num = Math.random() * (a - b) + b;
fixed && (num = Math.round((num) * fixed) / fixed);
return num;
},
/**获取两个数之间的随机整数*/
getInteger(a, b) {
return this.getDecimal(a, b, 1);
},
/**返回a到b且包含a和b的随机整数(其中a,b不能为负数)*/
get(a, b) {
return this.getInteger(a, b);
},
/**获取数组中的随机一个元素*/
valueFromArray(arr) {
if (arr && arr.length > 0) {
return arr[random.get(arr.length - 1)];
} else {
return arr;
}
},
/* 随机排序数组 */
sortArray: arr => arr.sort(() => Math.random() - 0.5),
/*获取数组中的随机多个元素组成的数组*/
arrayFromArray(arr, data) {
var tempArr = arr.concat();
data.randomTotal || (data.randomTotal = 0);//0代表获取任意多个随机元素,>0代表获取randomTotal个随机元素
data.startIndex || (data.startIndex = 0);//从数组开头随机的索引值
data.startIndex < 0 && (data.startIndex = 0);
data.endIndex || (data.endIndex = arr.length);//随机截止到尾部的索引值
data.endIndex <= data.startIndex && (data.endIndex = data.startIndex + 1);
data.endIndex > arr.length && (data.endIndex = arr.length);
data.isContinue || (data.isContinue = false);//是否获取连续随机元素
data.isRepeat || (data.isRepeat = false);//是否获取重复的元素
if (data.isContinue) {
var startIndex = data.randomTotal ? this.get(0, data.endIndex ? data.endIndex : tempArr.length - data.randomTotal) : this.get(0, tempArr.length);
startIndex < data.startIndex && (startIndex = data.startIndex);
var endIndex = data.randomTotal ? startIndex + data.randomTotal : this.get(startIndex, tempArr.length);
endIndex > data.endIndex && (endIndex = data.endIndex);
return tempArr.slice(startIndex, endIndex);
} else {
var newArr = [];
for (var i = 0, len = data.randomTotal || tempArr.length; i < len; i++) {
var randomIndex = this.get(data.startIndex > tempArr.length ? tempArr.length - 1 : data.startIndex, data.endIndex > tempArr.length - 1 ? tempArr.length - 1 : data.endIndex);
newArr.push(tempArr[randomIndex]);
data.isRepeat || tempArr.splice(randomIndex, 1);
}
return newArr;
}
}
};
//测试用例
console.log(random.arrayFromArray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], {
randomTotal: 3,
startIndex: 0,
endIndex: 10,
isContinue: true,
isRepeat: false
}));
/*边框渐变*/
border: 1px solid;
border-image: -webkit-linear-gradient(-45deg, rgba(255, 255, 255, 0.3) 0%, rgba(255, 255, 255, 0) 100%) 1 1; /* Safari 5.1 - 6.0 */
border-image: -o-linear-gradient(-45deg, rgba(255, 255, 255, 0.3) 0%, rgba(255, 255, 255, 0) 100%) 1 1; /* Opera 11.1 - 12.0 */
border-image: -moz-linear-gradient(-45deg, rgba(255, 255, 255, 0.3) 0%, rgba(255, 255, 255, 0) 100%) 1 1; /* Firefox 3.6 - 15 */
border-image: linear-gradient(-45deg, rgba(255, 255, 255, 0.3) 0%, rgba(255, 255, 255, 0) 100%) 1 1; /* 标准的语法(必须放在最后) */