【整理】【精华】【实用】常用代码片段(一)https://developer.aliyun.com/article/1476773
/**路径修复:因更换服务器图片路径指向错误的问题*/ 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); });
/*屏蔽拷贝图片________________________________________________*/ 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________________________ 屏蔽拷贝图片________________________*/
【整理】【精华】【实用】常用代码片段(三)https://developer.aliyun.com/article/1476778