積累的一個js公共庫,常用的功能封裝,base64和md5,toast等
阿新 • • 發佈:2018-12-12
-
對常用函式的封裝,有助於綜合運用和認時介面和程式碼層次;
一部分功能基於jQ,但是如果html中沒有引入jQ的話,該公共js會自動檢測並自動引入。
-
程式碼思路和用法再程式碼註釋和註釋呼叫中已經說明。
-
/* * create: 2018-06-00 update: 2018-09-18 unicode: UTF-8 * [email protected] * author: fyonecon * * js相容性:Android 5.0+,iOS 10.3+,IE 10+,主要面向移動裝置 * ES6(邏輯) + jQ(dom),但是可以不引入jQ,因為jQ會自動檢測並自動引入CDN * * 推薦CND: <script id="kd-jq" src="http://cdnaliyun.oss-cn-hangzhou.aliyuncs.com/js/jquery-1.11.3.min.js"></script> <script id="kd-js" charset="utf-8" src="http://cdnaliyun.oss-cn-hangzhou.aliyuncs.com/js/common.js"></script> * * VUE.js CDN: <script id="vue-dev" src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script id="vue-build" src="https://cdn.jsdelivr.net/npm/vue"></script> * * js、css線上壓縮: * https://tool.css-js.com * js加密 * https://www.sojson.com/jsobfuscator.html * * */ /* * 使用方法: 1. 直接引用方法函式即可,無Block函式那種繁瑣引用; 2. 注意一些自帶的全域性變數,避免一些坑; 3. 場景值可以解決多個或者多次呼叫同一函式的衝突,注意區分。 * * common.js函式呼叫表(主要已列出,次要的未列出): common.css自動引入,初始化了一些必要樣式 animated.css自動引入,預增加頁面動畫 無重新整理更改頁面地址,請參照 http://cdnaliyun.oss-cn-hangzhou.aliyuncs.com/js/js_extent_push.js 批量寫入css CDN連結 var cdn_css = ["", ""]; add_css(cdn_css) 字典轉陣列,return dictionary_to_array(input_data) 擴充套件js資料型別的判斷,return js_typeof(input_data) 圖片展示外掛 show_img(img_url, txt, refresh, display_btn) 獲取url的引數的值,return getThisUrlParam(url, key) 單個替換引數url裡面的老引數,輸出新url,return changeUrlParam(url, key, new_value) 批量替換引數url裡面的老引數,輸出新url,return changeAllUrlParam(str, arr) 過濾字串特殊符號,return getPureStr(str) 用於顯示[多文字Toast]提示 alert_txt(txt, time, call_func) 用於顯示[多文字確定]提示 alert_msg(title, content, btn_txt, this_func) 設定和更新cookie,return setCookie(key, value, expiredays) 讀取cookie,return getCookie(key) 時間戳轉日期,return timestampToTime(timestamp) 生成二維碼,回撥函式返回二維碼地址 make_qr(content, width, call_func) 求範圍內的值[min, max],return js_rand(min, max) 獲取當前時間的 日期、星期、時間戳(秒)、時間戳(毫秒),return getNowDate() 時間戳(毫秒)轉日期,輸入時間統一用秒,然後將毫秒轉換成秒,return formatDateTime(inputTime) 瀏覽器裝置運動事件(搖一搖、加速運動等) device_motion(call_func, during) 處理觸控手勢 呼叫swipe_touch(document.getElementById("test"));開啟該區域觸控事件 使用function touch_data(data){console.log(data);}取出該區域觸控引數 base64編碼解密加密,return js_base64_decode(result) js_base64_encode(string) 處理圖片 在img標籤中加入class="img-select-cell"即可完成 md5加密,return js_md5(string, toUpperCase, call_func) 判斷是否是微信瀏覽器的函式 user_weixin(status, jump_url, call_func, data) 判斷裝置型別,Android、iOS、PC user_device(device_func, data) 獲取使用者的地址和IP,回撥函式返回資訊陣列,return user_address(call_func) 頁面重新整理次數安全校驗,利用cookie refresh_check(max_num, common_cookie_pre, jump_url) 基於jQ的get方法請求 get_func(get_api_url, call_func) 基於jQ的post方法請求 post_func(post_api_url, obj, call_func) 原生get請求 get_api(get_api_url, call_func) 原生Fetch的post方法請求 post_api(post_api_url, obj, call_func) //頁面載入的百分比 [0~1],直接呼叫loading_percent(show_load)將使用預設載入效果 //loading_percent(show_load) 遮蔽層的開啟和刪除 show_layer(tag, bg_color, z_index) delete_layer(tag); 實現自定義的多次點選 many_click(_click_num, call_func) 或者直接呼叫 雙擊 two_click(call_func) 三擊 three_click(call_func) * * */ /* * * es6+php+oc * * */ // 'use strict'; // 暫不開啟這個功能 /* * 處理除錯模式 * */ //var common_debug = true; // bool: true時開啟除錯 if(typeof common_debug === "undefined"){ console.info("%c"+"'common_debug=false',console預設關閉", "color:blue;font-size:13px;"); common_debug = false; }else { if (common_debug === true){ console.info("%c"+"'common_debug=true',console預設開啟,unicode: UTF-8,2018-09-04", "color:green;font-size:13px;"); }else { console.info("%c"+"'common_debug=false',console已經關閉", "color:blue;font-size:13px;"); } } var common_debug_num = 1; // 參照 function console_info_func(txt) { // 日誌分流 if(common_debug_num === 1){ console.info("%c"+txt, "color:grey;font-size:12px;"); common_debug_num++; }else { //console.info(common_debug_num); common_debug_num++; } } /* * 重寫日誌輸出格式 * */ function common_log(txt) { // 日誌函式,注意,已經將其他資料型別強制轉化成了string common_debug === true ? console.info("%c" + txt, "color:#A0A0A0;font-size:12px;") : console_info_func("The common.js is running"); } /* * 擴充套件js框架 * */ const kd_jq = "http://cdnaliyun.oss-cn-hangzhou.aliyuncs.com/js/jquery-1.11.3.min.js" +'?'+time_milli(); // jq框架 const md5_url = "http://cdnaliyun.oss-cn-hangzhou.aliyuncs.com/js/md5.js" +'?'+time_milli(); // 引用md5.js const common_css = "http://cdnaliyun.oss-cn-hangzhou.aliyuncs.com/css/common.css" ; // 公共樣式 const qr_js= "http://cdnaliyun.oss-cn-hangzhou.aliyuncs.com/js/qrcode.js" +'?'+time_milli(); // js生成二維碼庫 const js_push = "http://cdnaliyun.oss-cn-hangzhou.aliyuncs.com/js/js_extent_push.js" +'?'+time_milli(); // 無重新整理更改頁面地址 const souhu_address = "http://pv.sohu.com/cityjson?ie=utf-8"; // 搜狐獲取使用者IP、城市統計 const animated_css = "http://cdnaliyun.oss-cn-hangzhou.aliyuncs.com/css/animate.min.css" ; // 動畫css3 (function (e) { var jq_check_num = 0; function run_jq_check(jq_check_num){ try { document.write('<link rel="stylesheet" class="common-css" href="'+common_css +'?'+time_milli()+'" />'); document.write('<link rel="stylesheet" class="animated-css" href="'+animated_css +'?'+time_milli()+'" />'); $("body").addClass("jQ-check1"); common_log("公共js載入正常"+jq_check_num); common_log("jQ檔案檢測正常"+jq_check_num); common_log("Cookies啟用否: "+navigator.cookieEnabled); var kd_jq_num = jq_check_num-1; for (let kd_i = 0; kd_i<kd_jq_num; kd_i++){ $(".kd-jq-num-"+kd_jq_num).remove(); } } catch(err){ common_log("公共js載入正常c_"+jq_check_num); common_log(err); var promise = new Promise(function(resolve, reject) { common_log("正在自動加入jQ框架..."); new_jQ=document.createElement("script"); new_jQ.setAttribute("type", "text/javascript"); new_jQ.setAttribute("class", "kd-jq-num-"+jq_check_num); new_jQ.setAttribute("src", kd_jq); document.head.appendChild(new_jQ); jq_check_num++; resolve(); }); promise.then(function() { common_log("正在檢測jQ..."); if (jq_check_num< 1){ // 檢測200 x 15 = 3s,超時不再檢測 run_jq_check(jq_check_num); }else { //$("body").addClass("jQ-check2"); common_log("jQ加入成功"); } }); } } run_jq_check(0); })("自檢"); /* * 這是一個遮蔽層,可能會用到。有了遮蔽層,可以防止譬如動畫期間的亂點選。 * tag 標識(指的是哪個標識,用於區分是哪個標識),bg_color 背景色, z_index fixed的軸 * */ function show_layer(tag, bg_color, z_index) { !tag ? _tag = 0 : _tag = tag; !bg_color ? _bg_color = "rgba(0,0,0,0)" : _bg_color = bg_color; !z_index ? _z_index = 80 : _z_index = z_index; $("body").append('<div class="bg-layer bg-layer-'+ _tag +'" style="position: fixed;width: 100%;height: 100%;background: '+ _bg_color +';top: 0;left: 0;z-index: '+ _z_index +';"></div>'); common_log("遮蔽層tag="+_tag+"已經建立,請及時刪除(請呼叫delete_layer(tag))"); } /* * 清除遮蔽層 * tag 標識(指的是要刪除哪個或者全部的遮蔽層) * */ function delete_layer(tag) { if (tag === "all"){ _tag = "all"; $(".bg-layer").remove(); }else { !tag ? _tag = 0 : _tag = tag; $(".bg-layer-"+_tag).remove(); } common_log("已經執行刪除tag="+_tag+"的刪除"); } /* * 404 * */ function jump_404(url) { if (url){ window.location.replace(url); }else { window.location.replace("https://m.sogou.com/404"); } } /* * 基礎函式 * 毫秒時間戳 * */ function time_milli() { var timestamp = Date.parse(new Date()); // 000毫秒時間戳 var milli = (new Date()).getMilliseconds(); // 純毫秒毫秒 var time_milli_res = timestamp + milli; //common_log(time_milli_res); return time_milli_res; } /* * 基礎函式 * 字典轉陣列 * */ function dictionary_to_array(input_data) { // 字典轉陣列 var new_arr = []; for (let i in input_data) { new_arr.push(input_data[i]); // 取value,不能取到key } //new_arr = Array.from(input_data); // es6 //console.log(new_arr); common_log("字典轉陣列:"+new_arr); // 已經強制array轉string return new_arr; } /* * 基礎函式 * js 具體的資料型別判斷,輸出準確的資料型別 * array dictionary null number string boolean undefined function * */ function js_typeof(input_data) { var this_type = typeof input_data; if (this_type === "object"){ // null {} [] if (input_data === null){ input_data = "null"; that_type = "null"; }else { if(input_data.constructor === Array){ // 陣列 that_type = "array for object"; }else if (input_data.constructor === Object){ // 字典型別,或者叫json input_data = dictionary_to_array(input_data); // 字典轉陣列 that_type = "dictionary(json) for object"; }else if(input_data.constructor === Date){ that_type = "date"; }else { that_type = this_type; } } }else{ // number string boolean undefined function that_type = this_type; } //console.log(input_data); common_log("資料型別:"+that_type+""+";值:"+input_data); return that_type; } /* * 預覽單個大圖功能:直接引用:show_img(img_url, "", "", "hide") * 可以判斷圖片地址是空或者404。 * * img_url:圖片地址或者圖片base64編碼 * txt:提示語 * refresh:"refresh" 關閉圖片預覽時重新整理, * display_btn: "hide" 關閉按鈕和圖層背景不顯示 * */ function show_img(img_url, txt, refresh, display_btn){ $("body").append('<div onclick="kd_layer_bg('+refresh+')" class="kd-layer-bg" style="position: fixed;width: 100%;height: 100%;top: 0;left: 0;z-index: 99980;background: rgba(0,0,0,0.5);"></div><img src="" onerror="kd_img_error()" class="kd-picture" id="kd-picture" alt="結果圖" style="position: absolute;top: 0;bottom: 0;width: 100%;left: 0;right: 0;margin: auto;z-index: 99988;padding-top: 30px;padding-bottom: 30px;min-height: 30px;max-width: 580px;display: block;"/>'); $(".kd-picture").attr("src", img_url); if(!img_url){ alert_txt("圖片地址為空!<br>無法預覽大圖", 3000); return; } $(".kd-layer-bg").show(300); $(".kd-picture").show(300).attr("src", img_url); if(!txt){ // 提示語 //alert_txt("長按可以儲存圖片哦~", 3000); }else{ alert_txt(txt, 3000); } if (display_btn === "hide"){ // 是否展示關閉按鈕 $(".kd-close-show_img").remove(); common_log("隱藏了-關閉-按鈕"); }else if(display_btn === "show"){ common_log("關閉-按鈕預設顯示1"); }else { common_log("關閉-按鈕預設顯示2"); } // 圖片高度超過一定範圍,操作背景按鈕不方便,即顯示一個另外的關閉圖片按鈕 var _img_url = img_url + "?" + Date.parse(new Date()); var img = new Image(); var patt = new RegExp("data:image/"); var res_base = patt.test(_img_url); if(res_base){ // 是base64 common_log("base64:"+res_base); $("body").append('<div class="kd-close-show_img" onclick="kd_layer_bg('+refresh+')" style="height: 32px;width: 55px;border-radius: 36px;text-align: center;line-height: 32px;border:2px solid #EEEEEE;font-size: 14px;color: antiquewhite;text-shadow: 0px 0px 10px #14727E;position: fixed;z-index: 99989;right: 20px;top: 25px;background: rgba(0,0,0,0.2);">關閉</div>'); }else{ // 不是base64 img.src = _img_url; img.onload = function(){ //alert('width:'+img.width+',height:'+img.height); var img_height = (img.height/img.width)*window.innerWidth; // 計算圖片的動態高度 common_log(img_height); if(Math.abs(img_height-window.innerHeight) < 60 || img_height-window.innerHeight>=60){ common_log("為特別高度圖提供關閉按鈕"); $("body").append('<div class="kd-close-show_img" onclick="kd_layer_bg('+refresh+')" style="height: 36px;width: 55px;border-radius: 36px;text-align: center;line-height: 36px;border:2px solid #EEEEEE;font-size: 14px;color: antiquewhite;text-shadow: 0px 0px 10px #14727E;position: fixed;z-index: 99989;right: 20px;top: 25px;background: rgba(0,0,0,0.1);">關閉</div>'); } }; } } // 圖片地址無效時 function kd_img_error(){ alert_txt("圖片地址無效!圖片404", 5000); setTimeout(function(){ kd_layer_bg(); }, 2000); // 丟擲圖片地址 common_log("圖片404地址:"+$(".kd-picture").attr("src")); } // 刪除圖片預覽節點 function kd_layer_bg(refresh){ $(".kd-layer-bg").remove(); $(".kd-picture").remove(); $(".kd-close-show_img").remove(); if(refresh === "refresh"){ window.location.reload(); }else if(!refresh){ //common_log("關閉圖層不重新整理頁面"); return; }else{ //common_log("關閉圖層不重新整理頁面"); return; } common_log("處理了圖片瀏覽圖層節點"); } /* * return * js獲取 url後的引數值,如果存在鍵,則返回鍵的值,如果不存在則返回null * string key: 鍵名,呼叫getUrlParam("sex")則返回0 * */ function getThisUrlParam(url, key) { // 返回值 // 相容模式url地址,例如:poop.html?page=3&ok=222#p=2#name=kd var url_str = ""; if(!url){ url_str = window.location.href; }else { url_str = url; } // 正則匹配url中的引數,如果存在鍵,則返回鍵的值,如果不存在則返回null var regExp = new RegExp("([?]|&|#)" + key + "=([^&|^#]*)(&|$|#)"); var result = url_str.match(regExp); if (result) { return decodeURIComponent(result[2]); // 轉義還原引數 } else { return null; // 沒有匹配的鍵即返回null } } /* * return * 單個替換引數url裡面的老引數,輸出新url * string url:網址或取他 * string key:鍵 * string new_value:新值 * */ function changeUrlParam(url, key, new_value) { // 返回新url var url_str = url; var regExp = new RegExp("([?]|&|#)" + key + "=([^&|^#]*)(&|$|#)"); var result = url_str.match(regExp); if (result) { var old_value = decodeURIComponent(result[2]); var old_str = key+"="+old_value; url_str = url_str.replace(new RegExp(old_str, "g"), key+"="+new_value); // 全域性替換 common_log("單個替換結果="+url_str); return url_str; } else { common_log("'"+url_str+"'中沒有匹配到key="+key+",new_value="+new_value); return url; // 沒有匹配的鍵即返回原始url } } /* * return * 批量替換引數url裡面的老引數,輸出新url * string str:網址或取他 * array arr: [[鍵, 新值], [key, new_value], [key, new_value]]; * * */ function changeAllUrlParam(str, arr) { // 返回新被替換過的url common_log("批量替換url中的鍵的值"); var url_str = str; var old_str = str; var array = arr; common_log(array); if(arr.length<=0 && typeof arr !== "object"){ common_log("arr引數錯誤:"+typeof arr+"=="+arr); return "arr is null"; } for(let kd= 0; kd<array.length; kd++){ var key = array[kd][0]; var new_value = array[kd][1]; url_str = changeUrlParam(url_str, key, new_value); } common_log("舊url="+old_str); common_log("新url="+url_str); return url_str; } /* * return * 過濾字串特殊符號: & | \\ * ^ % $ # @ . - * string str:要匹配的字串 * */ function getPureStr(str) { var pure_str=str.replace(/[&\|\\\*^%$#@.\-]/g, ""); // 去除特殊符號 return pure_str; } // 直接呼叫方法:alert_txt("提醒文字", time) // 用於顯示[多文字Toast]提示 // txt 文字字:最多幾十個字 // time 顯示時間:ms,long時為長時間(30分鐘)留存顯示 // function call_func 呼叫的函式名 var kd_ST = 0; var long_time = 0; var long_time_self = 0; function alert_txt(txt, time, call_func) { clearTimeout(kd_ST); // 清除老的定時器 clearTimeout(long_time); // 清除老的定時器 clearTimeout(long_time_self); // 清除老的定時器 $("body").append('<div class="kd-alert-txt select-none" style="padding-left:15px;padding-right:15px;padding-bottom:10px;margin:auto;position: fixed;z-index: 9999900;left: 0;right: 0;width: 250px;line-height: 24px;text-align: center;top: 0;bottom: 0;font-size: 13px;color: white;height: 140px;background: transparent;overflow-y: hidden;"><div class="kd-toast-txt" id="kd-toast-txt" style="padding-top:7px;padding-bottom:8px;overflow:hidden;letter-spacing:2px;background: rgba(0,0,0,0.8);border: 1px solid grey;border-radius: 5px;max-height: 93px;color: white !important;"> </div></div><div class="kd-alert-bg" style="position: fixed;z-index: 9999099;left: 0;top: 0;width: 100%;height:100%;background: rgba(0,0,0,0.1);"></div>'); if (!time){ time = 4000; } if(time === "long"){ // 超長時間提示 time = 1000*60*30; long_time = setTimeout(function () { // 定時執行,但是微信環境中,連結可能會被封殺,所以暫時沒有回撥 common_log("alert_txt()時間設定超時>'long 1000*60*30',但是並沒有設定超時時的回撥函式"); }, time); } if(time >= 1000*60*25){ var time_self = 1000*60*30; long_time_self = setTimeout(function () { // 定時執行,但是微信環境中,連結可能會被封殺,所以暫時沒有回撥 common_log("alert_txt()時間設定超時>1000*60*30,但是並沒有設定超時時的回撥函式"); }, time_self); } if ( txt.trim() === ""){ // 扔出錯誤 clearTimeout(kd_ST); alert_txt("系統報錯:txt文字為空<br>txt is null", 5000); return; } setTimeout(function () { $(".kd-toast-txt").html(txt); //document.getElementById("kd-toast-txt").innerHTML = txt; },80); kd_ST = setTimeout(function () { $(".kd-alert-txt").fadeOut(700).remove(); $(".kd-alert-bg").remove(); //_div.remove(); }, time); if(call_func){ call_func(); // 直接非同步呼叫 }else { common_log("alert_txt()沒有設定回撥函式"); } } // cookie字首 var cookie_pre = "le_"; // 示例:expiredays = 30 * 24 * 60 * 60 * 1000,30天 // 設定和更新cookie // function setCookie(key, value, expiredays){ // common_log("設定或更新cookie="+key+"="+value); // var exdate=new Date(); // exdate.setDate(exdate.getDate()+expiredays); // document.cookie=key+ "=" +escape(value) + ((expiredays==null) ? "" : ";expires="+exdate.toGMTString()); // } // // 讀取cookie // function getCookie(key){ // common_log("讀取cookie="+key); // if (document.cookie.length>0) { // c_start=document.cookie.indexOf(key + "="); // if (c_start!==-1){ // c_start=c_start + key.length+1; // c_end=document.cookie.indexOf(";",c_start); // if (c_end===-1) c_end=document.cookie.length; // return unescape(document.cookie.substring(c_start,c_end)); // } // } // return ""; // } //寫入cookies // time = 1*24*60*60*1000; function setCookie(name, value, time) { if (!time){ time = 1*24*60*60*1000; // 預設1天 } var exp = new Date(); exp.setTime(exp.getTime() + time); document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString(); } //讀取cookies function getCookie(name) { var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)"); if(arr=document.cookie.match(reg)){ return unescape(arr[2]); } else{ return null; } } //刪除cookies function delCookie(name) { var exp = new Date(); exp.setTime(exp.getTime() - 1); var cval=getCookie(name); if(cval!=null) { document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString(); } } // 時間戳轉日期 function timestampToTime(timestamp) { var date = new Date(timestamp * 1000);//時間戳為10位需*1000,時間戳為13位的話不需乘1000 Y = date.getFullYear() + '-'; M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-'; D = date.getDate() + ' '; h = date.getHours() + ':'; m = date.getMinutes() + ':'; s = date.getSeconds(); return Y+M+D+h+m+s; } // 生成二維碼,回撥函式返回二維碼地址,必要檔案qrcode.js function make_qr(content, width, call_func) { var _width = 200; if (!width){ common_log("make_qr()沒有設定寬,將預設200px"); }else { _width = width; } if (!content){ alert_txt("沒有設定二維碼內容"); } var _height = _width; $.getScript(qr_js, function (e) { common_log("生成二維碼"); // 生成二維碼 // 二維碼圖位置<img class="qr-img" id="qr-img" /> $("body").append('<div id="qrcode" class="qrcode" style="display: none;"></div>'); var qrcode = new QRCode("qrcode", { text: content, width: _width, height: _height, colorDark : "#000000", colorLight : '#ffffff', correctLevel : QRCode.CorrectLevel.L }); var qr_img_url = $(".qr-img").attr("src"); if (!call_func){ common_log("make_qr()無回撥函式"); }else { call_func(qr_img_url); } }); } /* * 求範圍內的值, */ function js_rand(min, max) { // [min, max] var this_rand = Math.floor(Math.random()*(max-min+1)+min); common_log("範圍內的隨機值="+this_rand); return this_rand; } /* * 將各個位數數字單獨取出,範圍[百億--百分位] */ function select_number(number) { var _number = []; if (typeof number === "number"){ // 正則方法 // var num = 123456; // var numArr = num.split(''); // //個位 // var a = numArr[numArr.length-1]; // //十位 // var b = numArr[numArr.length-2]; // //百位 // var c = numArr[numArr.length-3]; // //...以此類推 var _eleven = Math.floor(number/10000000000 % 10); // 百億 var _ten = Math.floor(number/1000000000 % 10); // 十億 var _nine = Math.floor(number/100000000 % 10); // 億 var _eight = Math.floor(number/10000000 % 10); // 千萬 var _seven = Math.floor(number/1000000 % 10); // 百萬 var _six = Math.floor(number/100000 % 10); // 十萬 var _five = Math.floor(number/10000 % 10); // 萬 var _four = Math.floor(number/1000 % 10); // 千 var _three = Math.floor(number/100 % 10); // 百 var _two = Math.floor(number/10 % 10); // 十 var _one = Math.floor(number % 10); // 個 var __one = Math.floor(number/0.1 % 10); // 十分位 var __two = Math.floor(number/0.01 % 10); // 百分位 _number = [number,_eleven,_ten,_nine,_eight,_seven,_six,_five,_four,_three,_two,_one,__one,__two]; common_log("範圍[原數0-百億1-個位11-百分位13]=="+_number+"=="+typeof _number+"==示例:個位[11]="+_number[11]); return _number; }else { common_log(typeof number); _number = [number,0,0,0,0,0,0,0,0,0,0,0,0,0]; common_log("資料型別錯誤,不可解析,各個位預設返回=="+_number); return _number; } } /* * * num 要匹配的數 * dot 是否迴圈出小數點後dot位,dot=2取到個位,dot=1取到十分位,dot=0取到百分位 * * */ function select_num(num, dot) { var num_array = select_number(num); if ( dot>2 || dot<0){ // dot取值異常時 common_log("取小數點位數異常,dot範圍:[0,2]"); return; }else if(typeof dot !== "number"){ common_log("將預設低位取到個位,dot=2"); dot = 2; } var j_num_max = 0; for (let j=0;j<num_array.length;j++){ var new_num_array = ["原數:"+num, "取小數dot[dot=2個位,dot=1十分位,dot=0百分位]:"+dot]; // 陣列第一個位原數 if(num_array[j+1]===0){ common_log("從左到右,改位位0,跳過"); }else { // 返回最高位 j_num_max = j+1; // 返回最高位 for (let m=j_num_max; m<num_array.length-dot; m++){ // 是否取出小數部分 //common_log("各個位數="+num_array[m]); new_num_array.push(num_array[m]); // 向陣列中新增新元素 } common_log("匹配值="+new_num_array); return new_num_array; break; // 找到最高位即刻跳出迴圈 } } } /* * 獲取當前時間的 日期、星期、時間戳(秒)、時間戳(毫秒) * */ function getNowDate() { var timestamp = Date.parse(new Date())/1000; // 精確到秒的時間戳 var date = new Date(); var sign1 = "-"; var sign2 = ":"; var year = date.getFullYear(); // 年 var month = date.getMonth() + 1; // 月 var day = date.getDate(); // 日 var hour = date.getHours(); // 時 var minutes = date.getMinutes(); // 分 var seconds = date.getSeconds(); // 秒 var milli = date.getMilliseconds(); // 毫秒 var weekArr = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']; var week = weekArr[date.getDay()]; // 給一位數資料前面加 “0” if (month >= 1 && month <= 9) { month = "0" + month; } if (day >= 0 && day <= 9) { day = "0" + day; } if (hour >= 0 && hour <= 9) { hour = "0" + hour; } if (minutes >= 0 && minutes <= 9) { minutes = "0" + minutes; } if (seconds >= 0 && seconds <= 9) { seconds = "0" + seconds; } var currentdate = [year + sign1 + month + sign1 + day, hour + sign2 + minutes + sign2 + seconds, week, timestamp, time_milli()]; common_log("當前時間[日期、星期、時間戳(秒)]陣列:"+currentdate); return currentdate; } /* * 時間戳(毫秒)轉日期,輸入時間統一用秒,然後將毫秒轉換成秒 * */ function formatDateTime(inputTime) { var s_time = inputTime*1000; var number = new Number(s_time); // 數字轉字串,以便計算長度 if (number.toString().length < 10 || number.toString().length > 14){ common_log("輸入時間戳單位為秒,特此提醒。當前數字長度:"+number.toString().length); } var date = new Date(s_time); var y = date.getFullYear(); var m = date.getMonth() + 1; m = m < 10 ? ('0' + m) : m; var d = date.getDate(); d = d < 10 ? ('0' + d) : d; var h = date.getHours(); h = h < 10 ? ('0' + h) : h; var minute = date.getMinutes(); var second = date.getSeconds(); minute = minute < 10 ? ('0' + minute) : minute; second = second < 10 ? ('0' + second) : second; var currentdate = [y+'-'+m+'-'+d, h+':'+minute+':'+second]; common_log("時間戳 轉 日期陣列:"+currentdate); return currentdate; } /* * * 瀏覽器裝置運動事件(搖一搖、加速運動等) * 瀏覽器相容性:Android(全)、iOS(全)執行正常 * 文件:https://developer.mozilla.org/zh-CN/docs/Web/API/DeviceMotionEvent * * call_func 回撥函式,此回撥函式不能攜帶引數,提前寫帶引數會造成device函式不能執行 * during 範圍[20ms, 3000ms] 。設定預設時間段內回撥一次,單位xx ms/次,預設500ms。 * * 例:function kd_func() { // 回撥函式 common_log("123"); alert_txt("123"); } device_motion(kd_func, 500); // 呼叫主函式 * * */ var SHAKE_THRESHOLD = 1000; // 預設動作時間差 var last_update = 0; var last_time = 0; var x; var y; var z; var last_x; var last_y; var last_z; var curTime; var isShakeble = true; // 除錯 function device_motion(call_func, during) { if(!during){ during = 500; }else if(during<20){ during = 20; }else if(during>3000){ during = 3000; } var first_time = new Date().getTime(); if (window.DeviceMotionEvent) { window.addEventListener('devicemotion', function (ev) { curTime = new Date().getTime(); var diffTime = curTime - last_update; if (diffTime > 100) { var acceleration = ev.accelerationIncludingGravity; last_update = curTime; x = acceleration.x; y = acceleration.y; z = acceleration.z; var speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000; if (speed > SHAKE_THRESHOLD && curTime - last_time > 1100 && isShakeble) { common_log("該裝置有加速事件,開始執行回撥函式"); // 處理回撥函式 if(call_func){ var cur_time = new Date().getTime(); if(Math.abs(first_time-cur_time) >= during){ common_log("呼叫了回撥函式"); first_time = new Date().getTime(); // 初始化 call_func(); // 呼叫函式。此回撥函式不能攜帶引數,提前寫帶引數會造成device函式不能執行 }else { common_log("由於時間段限制,跳過了回撥函式"); } }else { common_log("該裝置加速有效,但是沒有指定回撥函式。"); } } last_x = x; last_y = y; last_z = z; } }, false); common_log("該裝置支援位置和方向改變的速度,下一步,請讓裝置(瀏覽器)加速運動(搖一下裝置)起來。"); } else { common_log("該裝置(瀏覽器)不支援運動屬性"); alert_txt("該裝置(瀏覽器)不支援加速運動屬性"); } } /* * msg_func_ok(函式操作標識),需要coder使用時拿出來 * msg_func_close(函式操作標識),不需要自定義 * alert_msg(標題,內容描述或其它標籤內容,按鈕文字,函式操作標識[多個msg時區分各自操作]),不需要自定義 * 注意:this_func引數指的是標識數字或者標識字串,並不是函式 * */ /* function msg_func_ok(this_func) { // msg確定按鈕 ,示例 common_log("msg_ok標識="+this_func); switch(this_func){ case 1: run_test1(); break; case 8: run_test8(); break; default: common_log("發現未知操作標識="+this_func); } } function msg_func_close_call(this_func){ common_log("關閉msg的回撥函式,如果沒有,報錯可以忽略。"); } */ function msg_func_close(this_func) { // 關閉msg提示 common_log("msg_close標識="+this_func); $(".kd-alert-msg-div-"+this_func).remove(); $(".kd-alert-msg-bg-"+this_func).remove(); msg_func_close_call(this_func); } function alert_msg(title, content, btn_txt, this_func) { // 渲染msg // 校驗msg_func_ok()函式方法是否存在,因為這個是自定義函式 try { if(typeof msg_func_ok === "function") { //是函式 ,其中 msg_func_ok 為函式名稱 common_log("msg_func_ok(this_func)函式方法存在"); } else { //不是函式 common_log("msg_func_ok(this_func)函式方法不存在,將無法完成msg_func_ok按鈕的呼叫"); //alert_txt("msg_func_ok(this_func)函式方法不存在,將無法完成msg_func_ok按鈕的呼叫"); } if(typeof msg_func_close_call === "function") { //是函式 ,其中 msg_func_ok 為函式名稱 common_log("msg_func_close_call(this_func)函式方法存在"); } else { //不是函式 common_log("msg_func_close_call(this_func)函式方法不存在,不過這只是一個回撥函式,可以忽略報錯"); //alert_txt("msg_func_ok(this_func)函式方法不存在,將無法完成msg_func_ok按鈕的呼叫"); } } catch(e) { common_log("alert_msg(title, content, btn_txt, this_func)未知異常="+e); } // 校驗出現多個alert_msg()函式呼叫時,實現各自控制各自 if(!this_func){ var timestamp = Date.parse(new Date())/1000; // 精確到秒的時間戳 this_func = timestamp; common_log("沒有設定this_func的區別標識,將預設為="+this_func); } // 校驗必要引數 if(!title || !content || !btn_txt){ common_log("alert_msg引數不完整,this_func="+this_func); //alert_txt("alert_msg引數不完整,this_func="+this_func); return; } $("body").append('<div id="kd-alert-msg-bg select-none" class="kd-alert-msg-bg kd-alert-msg-bg-'+this_func+'" style="position: fixed;z-index: 9998000;width: 100%;height: 100%;background: rgba(0,0,0,0.6);top: 0;left: 0;"></div><div id="kd-alert-msg-div select-none" class="kd-alert-msg-div kd-alert-msg-div-'+this_func+'" style="width: 80%;max-width: 420px !important;position: fixed;z-index: 9999000;left: 0;right: 0;top: 0;bottom: 0;height: 360px;margin: auto;"><div id="kd-alert-msg" class="kd-alert-msg kd-alert-msg-'+this_func+'" style="padding-bottom: 10px;background: rgba(255,255,255,0.9);border:2px solid #EED5D2;border-radius: 3px;"><div style="padding: 8px 0 0 0;position: relative;padding-left: 10px;padding-right: 10px;"><div id="alert-msg-title" class="alert-msg-title alert-msg-title-'+this_func+'" style="width: 100%;font-size: 16px;color: #2F4F4F;border-bottom: 1px solid #EED5D2;padding-bottom: 10px;"><div id="alert-msg-title-text" class="alert-msg-title-text alert-msg-title-text-'+this_func+' " style="width: calc(100% - 40px);overflow-x: hidden;letter-spacing: 1px;overflow-y: hidden;white-space: nowrap;font-weight: 700;">提示</div></div><div id="alert-msg-title-close" class="alert-msg-title-close alert-msg-title-close-'+this_func+' click" style="position: absolute;right: 0;top: 0;font-size: 16px;padding-right: 15px;padding-top: -10px;padding-left: 20px;line-height: 38px;cursor: pointer;" onclick="msg_func_close('+this_func+')">X</div></div><div class="alert-msg-content alert-msg-content-'+this_func+'" style="padding-left: 15px;padding-right: 15px;padding-top: 2px;padding-bottom: 10px;line-height: 24px;font-size: 14px;letter-spacing: 1px;color: black;font-weight: 600;max-height: 200px;overflow-y: scroll;overflow-x: hidden;;min-height:50px">······</div><div style="padding-top: 10px;padding-bottom: 1px;text-align: center;"><div id="alert-msg-btn-ok" class=" alert-msg-btn-ok alert-msg-btn-ok-'+this_func+'" style="padding: 8px 25px;border-radius: 5px;background: #009ACD;color: white;font-size: 14px;display: inline-block;letter-spacing: 2px;cursor: pointer;" onclick="msg_func_ok('+this_func+')">···</div></div></div></div>'); $(".alert-msg-title-text-"+this_func).html(title); $(".alert-msg-content-"+this_func).html(content); $(".alert-msg-btn-ok-"+this_func).html(btn_txt) } var alert_msg_border = 1; try{ //kd-alert-msg-div $(document).on("click", ".kd-alert-msg-bg", function (e) { common_log("on"); if(alert_msg_border === 1){ $(".kd-alert-msg").css("border", "2px solid #7B68EE"); alert_msg_border = 2; }else { $(".kd-alert-msg").css("border", "2px solid #3CB371"); alert_msg_border = 1; } }); $(document).on("click", ".kd-alert-msg-div", function (e) { common_log("on"); if(alert_msg_border === 1){ $(".kd-alert-msg").css("border", "2px solid #CDCD00"); alert_msg_border = 2; }else { $(".kd-alert-msg").css("border", "2px solid #CD3700"); alert_msg_border = 1; } }); //alert_msg("提示", "這是內容1", "確定", 1); //alert_msg("提示", "這是內容2","確定", 8); //alert_msg("提示", "這是內容3","確定"); //alert_msg("提示", "這是內容4","確定"); }catch (err){ common_log(err); } /* * 基於jQ * get請求封裝 * void * get_api_url get介面 * call_func 回撥函式 * * */ function get_func(get_api_url, call_func) { $.getJSON(get_api_url, function(data, status){ common_log("get返回資料:" + data+";status:"+status+";返回資料的型別:"+typeof data); if(status === "success"){ if(!call_func){ common_log("回撥函式為必填!否則無法非同步返回結果"); }else { call_func(data); // 非同步得到結果 } }else{ common_log("請求錯誤,檢查後臺get方法"); alert_txt("請求錯誤或者網路不通"); } }); } /* * 基於jQ * post請求封裝 * void * post_url_api 介面 * dataObj 資料 * call_func 回撥函式 * */ function post_func(post_url_api, dataObj, call_func) { var post_url = post_url_api; var obj = dataObj; // 請求資料 $.ajax({ url: post_url, type: "POST", dataType: "json", // 已經預設json async: true, // 已經預設true data: obj, // dataObj為Object型別: {nickname: "name",} success: function(data, status){ common_log("post返回資料:" + data+";status:"+status+";返回資料的型別:"+typeof data); // 確保返回資料是object型別 if(typeof data === "string"){ datas = JSON.parse(data); // json字串轉換成json物件 }else { datas = data; } if(!call_func){ common_log("回撥函式為必填!否則無法非同步返回結果"); }else { call_func(datas); // 非同步得到結果 } }, error: function (xhr) { console.log(xhr); alert_txt("介面請求錯誤或者網路不通"); } }); } /* * * 基於ES,或者原生js * get請求封裝 * * */ function get_api(get_api_url, call_func) { //請求資料庫存在的使用者資訊 var url = get_api_url; var ajax_get = function(url) { return new Promise(function(resolve2, reject) { var r = new XMLHttpRequest(); r.open("GET", url, true); r.onreadystatechange = function () { if (r.readyState !== 4 || r.status !== 200) return; var data = r.responseText; resolve2(data); // 確保返回資料是object型別 if(typeof data === "string"){ datas = JSON.parse(data); // json字串轉換成json物件 }else{ datas = data; } if(!call_func){ common_log("回撥函式為必填!否則無法非同步返回結果"); }else { call_func(datas); // 非同步得到結果 } }; r.send(); }) }; ajax_get(url); } /* * * 基於ES,或者原生js * post請求封裝 * 貌似不能上傳大於2M的base64,原因未知 * * */ function post_api(post_api_url, dataObj, call_func) { var url = post_api_url; var obj = dataObj; // object型別: {nickname: "name",} fetch(url,{ method:"POST", mode: "cros", headers:{ "Content-type":"application/x-www-form-urlencoded; charset=UTF-8" }, body: JSON.stringify(obj) }) .then(function (response){ common_log(response); }) .then(function(data){ common_log("fetch請求成功,響應資料為:", data); // 確保返回資料是object型別 if(typeof data === "string"){ datas = JSON.parse(data); // json字串轉換成json物件 }else{ datas = data; } if(!call_func){ common_log("回撥函式為必填!否則無法非同步返回結果"); }else { call_func(datas); // 非同步得到結果 } }) .catch(function(err){ common_log("Fetch錯誤:"+err); alert_txt("介面請求錯誤或者網路不通"); }); } /* * * base64編碼語解碼 * Base64 encode / decode * 文件:https://blog.csdn.net/u011127019/article/details/51673230 * */ function Base64() { // private property _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; // public method for encoding this.encode = function (input) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; input = _utf8_encode(input); while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4); } return output; } // public method for decoding this.decode = function (input) { var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (i < input.length) { enc1 = _keyStr.indexOf(input.charAt(i++)); enc2 = _keyStr.indexOf(input.charAt(i++)); enc3 = _keyStr.indexOf(input.charAt(i++)); enc4 = _keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 != 64) { output = output + String.fromCharCode(chr2); } if (enc4 != 64) { output = output + String.fromCharCode(chr3); } } output = _utf8_decode(output); return output; } // private method for UTF-8 encoding _utf8_encode = function (string) { string = string.replace(/\r\n/g,"\n"); var utftext = ""; for (let n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; } // private method for UTF-8 decoding _utf8_decode = function (utftext) { var string = ""; var i = 0; var c = c1 = c2 = 0; while ( i < utftext.length ) { c = utftext.charCodeAt(i); if (c < 128) { string += String.fromCharCode(c); i++; } else if((c > 191) && (c < 224)) { c2 = utftext.charCodeAt(i+1); string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); i += 2; } else { c2 = utftext.charCodeAt(i+1); c3 = utftext.charCodeAt(i+2); string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); i += 3; } } return string; } } var base = new Base64(); //1.加密 // var str = '124內容'; // var result = base.encode(str); // //2.解密 // var result2 = base.decode(result); // base64加密 function js_base64_encode(string) { var result = base.encode(string); common_log("js_base64加密結果="+result); return result; } // base64解密,預設1次解密 var js_base64_j = 1; function js_base64_decode(result){ var string = base.decode(result); common_log("js_base64解密(第"+js_base64_j+"次解密)="+string); js_base64_j++; return string; } /* * * 處理圖片 * 在img標籤中加入class="img-select-cell"即可完成 * * */ var img_src = ""; // 當前圖片地址 try { $(document).on("click", ".img-select-cell", function (e) { // 消除append()帶來的不可點選 var that = $(this); img_src = that.attr("src"); var timestamp = Date.parse(new Date())/1000; // 精確到秒的時間戳 $("body").append('<div class="select-none img-select-cell-bg" onclick="img_select_bg(1)" style="position: fixed;left: 0;top: 0; z-index: 998500;background: rgba(0,0,0,0.5);width: 100%;height: 100%;"></div>' + '<div class="img-select-cell-div pc-width-780 select-none" style="width: 280px;margin-left: auto;margin-right: auto;position: fixed;z-index: 998700;left: 0;right: 0;bottom: 0;min-height: 100px;"><div style="margin-bottom: 10px;">' + '<div class="img-select-cell-item-show" style="height: 45px;line-height: 45px;text-align: center;font-size: 14px;white-space: nowrap;overflow: hidden;letter-spacing: 1px;color: #363636;font-weight: 600;margin-bottom: 1px;background: white;border-radius: 3px;">檢視大圖</div>' + '<div class="img-select-cell-item img-select-down" style="height: 45px;line-height: 45px;text-align: center;font-size: 14px;white-space: nowrap;overflow: hidden;letter-spacing: 1px;color: #363636;font-weight: 600;margin-bottom: 1px;background: white;border-radius: 3px;">擷取圖片</div>' + '<div class="img-select-cell-item img-select-download-this" style="height: 45px;line-height: 45px;text-align: center;font-size: 14px;white-space: nowrap;overflow: hidden;letter-spacing: 1px;color: #363636;font-weight: 600;margin-bottom: 1px;background: white;border-radius: 3px;">儲存圖片</div>' + '</div><div class="img-select-cell-close click hover" style="height: 45px;line-height: 45px;text-align: center;font-size: 14px;white-space: nowrap;overflow: hidden;letter-spacing: 3px;color: #4876FF;font-weight: 600;margin-bottom: 70px;background: white;border-radius: 5px;" onclick="img_select_bg(2)">取消</div></div>'); }); $(document).on("click", ".img-select-down", function (e) { //common_log("down"); if(!img_src){ alert_txt("沒有圖片地址,不能下載"); return; } // window.open(img_src); window.location.href=img_src; setTimeout(function () { img_select_bg(4); }, 500) }); $(document).on("click", ".img-select-download-this", function (e) { //common_log("down"); if(!img_src){ alert_txt("沒有圖片地址,不能下載"); return; } downloadIamge(".img-select-download-this", "img-name", img_src); setTimeout(function () { img_select_bg(4); }, 500) }); $(document).on("click", ".img-select-cell-item-show", function (e) { if(!img_src){ alert_txt("沒有圖片地址,不能檢視大圖"); return; } show_img(img_src, "", "", "hide"); img_select_bg(5); }); } catch (err){ common_log(err); } function img_select_bg(num) { // 關閉圖層操作 common_log("關閉select-cell="+num); $(".img-select-cell-div").remove(); $(".img-select-cell-bg").slideUp(50); setTimeout(function () { // $(".img-select-cell-div").remove(); $(".img-select-cell-bg").remove(); }, 50) } // 下載圖片 function downloadIamge(selector, name, url) { alert_txt("正在儲存"); // 通過選擇器獲取img元素, var img = document.querySelector(selector); // 將圖片的src屬性作為URL地址 var _url = url; var a = document.createElement("a"); var event = new MouseEvent('click'); a.download = name; a.href = _url; a.dispatchEvent(event); } /* * * md5加密: * js_md5(要加密的字串; 輸出是否為大寫,A或者1) * string 要加密的 * toUpperCase 是否大小寫 * call_func 回撥函式 * */ var md5_res = ""; function js_md5(string, toUpperCase, call_func) { $.getScript(md5_url,function (e) { //common_log("md5.js自動引用成功"); md5_res = hex_md5(string); if(toUpperCase === "A" || toUpperCase === 1){ // 大寫轉換 md5_res = md5_res.toUpperCase(); } common_log("js_md5方法加密結果="+md5_res); if(!call_func){ common_log("js_md5()無回撥函式"); }else { call_func(md5_res); } }); } // function md5_log(this_md5){ // console.log(this_md5); // } // js_md5("123", "", md5_log); /* * 判斷是否是微信瀏覽器的函式 * status: "on","off" * jump_url: 跳轉的url,為空值時執行回撥函式,不為空時執行跳轉操作 * call_func: 回撥函式 * 傳遞引數:提示語 * 場景值weixin_res: * 1 是微信瀏覽器,然後執行任何操作; * 0 不是微信瀏覽器但不執行任何操作; * -1 不是微信瀏覽器,要執行某個操作; * 2 不是微信瀏覽器,錯誤操作,要執行某個操作。 * * */ function user_weixin(status, jump_url, call_func, data){ var ua = window.navigator.userAgent.toLowerCase(); var weixin_res = 0; // 場景值 //通過正則表示式匹配ua中是否含有MicroMessenger字串 if(ua.match(/MicroMessenger/i) === "micromessenger"){ common_log("is weixin"); weixin_res = 1; }else{ if(jump_url === ""){ if (status === "on"){ common_log("not weixin,on"); weixin_res = -1; }else if (status === "off"){ common_log("not weixin,off"); weixin_res = 0; }else{ common_log("user_weixin()約定引數不正確1"); weixin_res = 2; } if(!call_func){ common_log("call_func引數為空"); }else { call_func(weixin_res, data); } }else{ // 有jump_url代表需要立即執行跳轉操作,並不需要任何回撥 if (status === "on"){ common_log("not weixin,on"); }else if (status === "off"){ common_log("not weixin,off"); return; }else{ common_log("user_weixin()約定引數不正確2"); return; } window.location.replace(jump_url); } } } /* * * 判斷裝置型別 * Android、iOS、PC * android_func(1) android回撥函式 * ios_func(2) ios回撥函式 * pc_func(3) pc回撥函式 * data 傳入引數 * * */ function user_device(device_func, data){ var datas = data; // 攜參 var u = navigator.userAgent; var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android終端 var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios終端 if (isAndroid === true || isiOS === false){ // android console.log("Android"); device_func(1, datas); }else if(isAndroid === false || isiOS === true){ // ios console.log("iOS"); device_func(2, datas); }else { // pc console.log("PC"); device_func(3, datas); } } /* * void * 獲取使用者的地址和IP,回撥函式返回資訊陣列 * 使用方法: * call_func(user_addr); // 成功時的回撥函式,將引數返回window,解決一部問題 * 頁面載入時就要引用user_address(),請呼叫全域性變數user_addr=,若出現數組為空,請使用window.onload = function(e){ user_addr= }; * */ var user_addr = []; function user_address(call_func) { $.getScript(souhu_address, function (e) { var user_ip = returnCitySN["cip"]; // ip var user_city = returnCitySN["cname"]; // 省市 var user_time = Date.parse(new Date())/1000; // 精確到秒的時間戳 user_addr = [user_ip, user_city, user_time]; js_typeof(user_addr); // 顯示資料型別 common_log("頁面載入時就要引用user_address(),請呼叫全域性變數user_addr="+user_addr); //return user_addr; if(!call_func){ common_log("無回撥函式將結果轉發出來,請注意非同步問題"); }else { call_func(user_addr); // 成功時的回撥函式,將引數返回window,解決一部問題 } }); } // function user_address_log(this_addr){ // console.log(this_addr); // } // user_address(user_address_log); /* * * 頁面重新整理次數安全校驗,利用cookie * max_num最大重新整理次數 * jump_url超過最大重新整理次數時的跳轉地址,一般為404頁 * */ //var common_cookie_pre = "refresh_page_number_"; function refresh_check(max_num, common_cookie_pre, jump_url) { var _jump_url = jump_url; var _max_num = max_num; var _common_cookie_pre = common_cookie_pre; if(!_common_cookie_pre){ _common_cookie_pre = "refresh_page_number_"; } if(!_jump_url){ _jump_url = "https://m.sogou.com/404"; } if(_max_num < 3){ common_log("頁面最大訪問數有誤,不能<=2"); _max_num = 3; } var _time = 2*24*3600000; var max_num_i = getCookie(_common_cookie_pre+"jump_num")*1; // string 轉 number if(!max_num_i){ max_num_i = 1; }else { max_num_i +=1; } if(navigator.cookieEnabled !== true){ // 不支援cookie時直接跳轉走 window.location.replace(_jump_url); }else { if(max_num_i > _max_num){ setTimeout(function () { window.location.replace(_jump_url); }, 2000); }else { setCookie(common_cookie_pre+"jump_num", max_num_i, _time); } } } //refresh_check(1000, "kd_", ""); /* * 批量寫入css CDN連結 * 利用時間戳自動消除css快取 * */ function add_css(_cdn_css){ var html_css = _cdn_css; if (typeof(_cdn_css) === "undefined"){ common_log("css的CDN,_cdn_css=[];未定義"); return; } if(js_typeof(html_css) === "array"){ for (let css_i=0; css_i < html_css.length; css_i++) { if (!html_css[css_i]){ common_log("css_null"); break; // 遇到錯誤,直接跳出,不用再執行 }else{$("head").append('<link rel="stylesheet" class="html-css" href="'+ html_css[css_i] +'?'+time_milli()+'" />'); } } }else{ common_log(js_typeof(html_css)); } } // var cdn_css = [ // css CDN // "", // ]; //add_css(cdn_css); function show_loading() { // 顯示載入動畫 $(".content").append('<div id="app-loading" class="app-loading flex-center"><div class="loading-icon"></div></div>') $(".app-loading").css("background", "rgba(0, 0, 0, 0.1)"); } function delete_loading() { // 刪除載入動畫 $(".app-loading").remove(); } /* * 長按事件 * long_press(_id, call_func) * */ function long_press(_id, call_func){ let timer = null; _id.addEventListener("touchstart",function(){ timer = setTimeout(function () { call_func(_id); },1200); // 定義長按時間 }); _id.addEventListener("touchend",function(){ clearTimeout(timer); }); } // long_press(_id, test_func); // function test_func(){ // // } /* * 處理觸控手勢 * swipe_touch(_id) * 呼叫swipe_touch(document.getElementById("test"));開啟該區域觸控事件 * 使用function touch_data(data){console.log(data);}取出該區域觸控引數 * */ function swipe_touch(_id, call_func, long){ if (long === "long"){ long_press(_id, call_func); return; } let startx; let endx; let starty; let endy; function _touch_cons(){ let dir_x = "center_x"; let dir_y = "center_y"; if(startx > endx){dir_x = "left";}else if(startx < endx){dir_x = "right";} if(starty > endy){dir_y = "up";}else if(starty < endy){dir_y = "down";} let _data = { "dir_x": dir_x, "x1" : Math.floor(startx), "x2" : Math.floor(endx), "dir_y": dir_y, "y1" : Math.floor(starty), "y2" : Math.floor(endy), "id" : _id, }; if (!call_func){ try{ touch_data(_data); }catch (e) { // 必選日誌列印 console.info("請使用function touch_data(data){console.log(data);}取出該區域觸控引數"); } }else { call_func(_data); } } _id.addEventListener("touchstart",function(e){ let touch=e.changedTouches; startx=touch[0].clientX; starty=touch[0].clientY; }); _id.addEventListener("touchend",function(e){ let touch=e.changedTouches; endx=touch[0].clientX; endy=touch[0].clientY; _touch_cons(); }); } // function touch_data(data) { // console.log(data); // // } /* * 實現自定義的N次連續點選 * many_click(_click_num, call_func) * 必填:_click_num 點選次數 [1, 10] * 必填:call_func 回撥函式 * 選填:_id 是長按手勢傳入的目標標籤id * */ let click_before_time = 0; let click_num = 0; function many_click(_click_num, call_func, _id){ if (!call_func){console.info("many_click(_click_num, call_func)無回撥函式"); return;} if (_click_num === "long"){ /*實現長按*/ if(!_id){console.info("_id為必填。many_click('long', call_func, _id)"); return;} long_press(_id, call_func); return; } // 安全校驗 if (typeof _click_num !== "number"){ console.info("many_click(_click_num, call_func)的點選次數為number型別"); return; } // 處理click_num的新值情況 if(click_num === 0){ click_num = _click_num; }else { if (click_num < 1 || click_num > 10){ click_num = 1; } /*只准1擊至10擊,其他情況預設1擊*/ } // 處理點選之時差 let click_time = Date.parse(new Date())+(new Date()).getMilliseconds(); // 毫秒時間戳 if( (click_time - click_before_time) < 400 ){ // 下一次點選是否成功 click_before_time = Date.parse(new Date())+(new Date()).getMilliseconds(); click_num--; }else{ // 第一次點選 click_before_time = Date.parse(new Date())+(new Date()).getMilliseconds(); if(click_num < _click_num){ /*清除歷史不成功點選的引數*/ click_num = _click_num; } } // N次成功點選後啟用回撥函式,並初始化click_num if (click_num === 1){ call_func("回撥函式不需要傳參"); click_num = 0; /*初始化點選次數*/ } } /* * 雙擊 * */ function two_click(call_func) { many_click(2, call_func); } /* * 三擊 * */ function three_click(call_func) { many_click(3, call_func); } //====開始====處理舊的仍舊線上的函式==== /* * update 2018-08-15 * 由於對函式命名或者引數寫法上的更新,導致舊的仍舊線上的函式不能正常使用, * 所以需要【用老函式名轉發一下新函式及新函式帶引數的方式】 * * */ /* * 匹配url引數 * */ function getUrlParam(key) { // 返回值 common_log('getThisUrlParam("", key)已經接管了getUrlParam(key)'); return getThisUrlParam("", key); } /* * 判斷微信瀏覽器 * */ function isWeiXin(txt, status, url){ common_log(txt); common_log('user_weixin(status, url)已經接管了isWeiXin(txt, status, url)'); user_weixin(status, url); } //====結束====處理舊的仍舊線上的函式====
-
-