今年工作進度到這裡結束,整理一下今年收集的自用js庫,後期會更新,代碼已貼github=>https://github.com/lpg-kobe/personal-github /** * @param {long} //通用函數庫 * @param {onerror} //js錯誤調試 * @au ...
今年工作進度到這裡結束,整理一下今年收集的自用js庫,後期會更新,代碼已貼github=>https://github.com/lpg-kobe/personal-github
/** * @param {long} //通用函數庫 * @param {onerror} //js錯誤調試 * @author lpg 2017-11-02 */
window.onerror = function (errorMessage, scriptURI, lineNumber, columnNumber, errorObj) { console.log("錯誤信息:", errorMessage); console.log("出錯文件:", scriptURI); console.log("出錯行號:", lineNumber); console.log("出錯列號:", columnNumber); console.log("錯誤詳情:", errorObj); }
var eventUtils = {//跨瀏覽器事件 getEvent: function (event) {//獲取事件 return event ? event : window.event }, addHandler: function (ele, type, handler) {//事件監聽 if (ele.addEventListener) { ele.addEventListener(type, handler) } else if (ele.attachEvent) { ele.attachEvent('on' + type, handler) } else { ele['on' + type] } }, removeHandler: function (ele, type, handler) {//移除監聽 if (ele.removeEventListener) { ele.removeEventListener(type, handler) } else if (ele.attachEvent) { ele.detachEvent('on' + type, handler) } else { ele['on' + type] } }, getTarget: function (event) {//事件目標 if (event.target) { return event.target } else { return event.srcElement } }, preventDefault: function (event) {//阻止預設事件 if (event.preventDefault) { return event.preventDefault } else { return event.returnValue = false } }, stopPropagation: function (event) {//阻止冒泡 if (event.stopPropagation) { return event.stopPropagation } else { return event.cancelBubble = true } } } /* *通用ajax請求 *需引入jq庫支持 */ var xhr = { ajaxRequest(options = { type: 'Get' }) {//同步ajax var ajax = { type: options.type, url: options.url, data: options.data, dataType: 'json', xhrFields: { withCredentials: true }, crossDomain: true }; ajax.success = (result) => { console.log(result) }; $.ajax(ajax) }, async asyncRequest(options = { type: 'Get' }) {//非同步ajax return new promise((resolve, reject) => { var ajax = { type: options.type, url: options.url, data: options.data, dataType: 'json', async: true, xhrFields: { withCredentials: true }, crossDomain: true }; ajax.success = (result) => { resolve(result); console.log(result) }; ajax.error = (error) => { resolve(error) }; $.ajax(ajax) }) } }
/** * @param {httpGet()}老版本http請求 * @method => httpGet({'請求url','傳輸data','回調函數'}) */
function httpGet(services, data, callback) { var url = 'example'; $.ajax({ url: url, data: data, dataType: 'json', xhrFields: { withCredentials: true }, crossDomain: true, success: function (data) { var info = data['data']['info'];//返回數據格式視情況而定 if (data['ret'] == 200 && data['data']['code'] == 0) { callback(info); } else { if (data['data']['code'] == 700) { return; } var msg = data['data'] && data['data']['msg'] ? data['data']['msg'] : ''; msg = msg == '' && data['msg'] ? data['msg'] : msg; //xhr.showmsg(msg); } }, error: function (data) {
} }) }
/* 封裝ajax函數 1 * @param 簡易原生ajax 2 * @param {string}opt.type http連接的方式,包括POST和GET兩種方式 3 * @param {string}opt.url 發送請求的url 4 * @param {boolean}opt.async 是否為非同步請求,true為非同步的,false為同步的 5 * @param {object}opt.data 發送的參數,格式為對象類型 6 * @param {function}opt.success ajax發送並接收成功調用的回調函數 7 */ function Ajax(opt) { opt = opt || {}; opt.method = opt.method.toUpperCase() || 'POST'; opt.url = opt.url || ''; opt.async = opt.async || true; opt.data = opt.data || null; opt.success = opt.success || function () { }; var xmlHttp = null; if (XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } else { xmlHttp = new ActiveXObject('Microsoft.XMLHTTP'); }; var params = []; for (var key in opt.data) { params.push(key + '=' + opt.data[key]); } var postData = params.join('&'); if (opt.method.toUpperCase() === 'POST') { xmlHttp.open(opt.method, opt.url, opt.async); xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8'); xmlHttp.send(postData); } else if (opt.method.toUpperCase() === 'GET') { xmlHttp.open(opt.method, opt.url + '?' + postData, opt.async); xmlHttp.send(null); } xmlHttp.onreadystatechange = function () { if (xmlHttp.readyState == 4 && xmlHttp.status == 200) { opt.success(xmlHttp.responseText); } }; }
/** * 分頁載入器 * @type {Function} * 方法可擴展 */
function pagingLoad(options) { //分頁載入 if (!document.getElementById('load_txt')) { this.loadTxt = document.createElement('div'); loadTxt.id = "load_txt"; loadTxt.style.textAlign = "center"; document.body.appendChild(loadTxt); }; this.oPageLoad = { page: 1, el: options.el, //滾動的對象 apiUrl: options.url, data: options.data || {}, tailload: true, sucload: true, totalpage: options.totalpage, //總頁數 containArea: options.containArea, //內容區 callback: options.callback }; var _this = this; this.oPageLoad.el.onscroll = function () { var scrollTop = this.scrollTop, //滾動條距頂部的高度 containHei = _this.oPageLoad.containArea.scrollHeight, //內容高度(scrollHeight) clientHei = this.clientHeight; //可視高度 console.log('當前總頁數' + _this.oPageLoad.totalpage, scrollTop, containHei, clientHei); if (_this.oPageLoad.page == _this.oPageLoad.totalpage && containHei - scrollTop - clientHei < 20) { //判斷頁碼是否等於總頁碼且滾動條到達最底部 if (_this.oPageLoad.tailload) { _this.loadTxt.innerHTML = "已全部載入完成"; _this.oPageLoad.tailload = !_this.oPageLoad.tailload; return; } else { _this.loadTxt.innerHTML = "已全部載入完成"; return; } };
if (containHei - scrollTop - clientHei < 20 && _this.oPageLoad.sucload) { _this.oPageLoad.page++; _this.oPageLoad.sucload = !_this.oPageLoad.sucload; _this.loadTxt.innerHTML = "載入中..."; console.log('loading...第' + _this.oPageLoad.page + '頁'); _this.oPageLoad.data["page"] = _this.oPageLoad.page; httpGet(_this.oPageLoad.apiUrl, _this.oPageLoad.data, function (data) {//請求載入 commonArray = commonArray.concat(data); if (pagingLoadOption.containArea == document.getElementById('successList')) {//區分區塊分區載入 var $successData = template('success_list', {info: commonArray,timeFormat: timeFormat }); $("#successList").html($successData); } else { var $inviteData = template('invite_list', {info: commonArray,timeFormat: timeFormat }); $("#inviteList").html($inviteData); }; _this.loadTxt.innerHTML = ""; _this.oPageLoad.sucload = !_this.oPageLoad.sucload; });
};
};
}
/** * @param {function} 實用函數 * @method => bVersion()判斷瀏覽器內核信息EXP:if(bVersion.iwx) * @method => getExplore獲取瀏覽器類型和版本,EXP:return Safari:9.0 * @method => toArray(['1','2'],2)仿Array.shift()方法從頭部清除數組指定長度並返回新數組 * @method => initRun() 根據設備視口clientWidth寬度調節字體大小(基於750px寬度設計稿設置跟元素字體大小20px==1rem) * @method => getQueryString() 獲取url鏈接中參數對應的值 * @method => setStore(key, value) 本地存儲key的value * @method => getStore(key, exp, name) 取存儲的數據:key[名稱]exp[過期時間]name[指定命名的變數] * @method => hasClass(ele,cls)判斷element節點是否存在clasName('cls') * @method => addClass(ele,cls)在hasClass判斷基礎上添加clasName('cls') * @method => removeClass(ele,cls)在hasClass判斷基礎上移除clasName('cls') * @method => getCookie(name)獲取名為name的cookie值cookName[0]為鍵名,cookName[1]為鍵值 * @method => setCookie(name,value,days)設置過期時間戳expires為days名為name值為value的cookie * @method => removeCookie(name)重新設置過期的cookie即可移除 * @method => randomColor生成隨機顏色#xxxxxx * @method => randomNum生成指定範圍的隨機數(min-max) * @method => isPhoneNum(str)是否為手機號 */
var utils = { bVersion: function () { var u = navigator.userAgent; return { //移動終端瀏覽器內核信息 trident: u.indexOf('Trident') > -1, //IE內核 presto: u.indexOf('Presto') > -1, //opera內核 webKit: u.indexOf('AppleWebKit') > -1, //蘋果、谷歌內核 gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐內核 mobile: !!u.match(/AppleWebKit.*Mobile.*/) || !!u.match(/AppleWebKit/), //是否為移動終端 ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios終端 android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android終端或者uc瀏覽器 iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否為iPhone或者QQHD瀏覽器 iPad: u.indexOf('iPad') > -1, //是否iPad iwx: /MicroMessenger/i.test(u),//是否微信 iWeiBo: /Weibo/i.test(navigator.userAgent)//微博客戶端 }; }(),
getExplore: function () {//獲取瀏覽器類型和版本 var sys = {}, ua = navigator.userAgent.toLowerCase(), s; (s = ua.match(/rv:([\d.]+)\) like gecko/)) ? sys.ie = s[1] : (s = ua.match(/msie ([\d\.]+)/)) ? sys.ie = s[1] : (s = ua.match(/edge\/([\d\.]+)/)) ? sys.edge = s[1] : (s = ua.match(/firefox\/([\d\.]+)/)) ? sys.firefox = s[1] : (s = ua.match(/(?:opera|opr).([\d\.]+)/)) ? sys.opera = s[1] : (s = ua.match(/chrome\/([\d\.]+)/)) ? sys.chrome = s[1] : (s = ua.match(/version\/([\d\.]+).*safari/)) ? sys.safari = s[1] : 0;
// 根據關係進行判斷 if (sys.ie) return ('IE: ' + sys.ie)
if (sys.edge) return ('EDGE: ' + sys.edge)
if (sys.firefox) return ('Firefox: ' + sys.firefox)
if (sys.chrome) return ('Chrome: ' + sys.chrome)
if (sys.opera) return ('Opera: ' + sys.opera)
if (sys.safari) return ('Safari: ' + sys.safari)
return 'Unkonwn' },
toArray(arr, len) { len = len || 0; var i = arr.length - len; var ret = new Array(i); while (i--) { ret[i] = arr[i + len]; } console.log(ret); return ret },
hasClass: function (ele, cls) {//true||false return (new RegExp('(\\s|^)' + cls + '(\\s|$)')).test(ele.className); },
addClass: function (cls) { if (!hasClass(ele, cls)) { ele.className += '' + cls; } },
removeClass: function (cls) { if (hasClass(ele, cls)) { var exp = new RegExp('(\\s|^)' + cls + '(\\s|$)'); ele.className = ele.className.replace(exp, ' '); } },
getCookie: function (name) { var cookArr = document.cookie.replace(/\s/g, "").split(';'); for (var i = 0, len = cookArr.length; i < len; i++) { var cookName = cookArr[i].split('='); if (cookName[0] == name) { return decodeURIComponent(cookName[1]); } }; return ''; },
setCookie: function (name, value, days) { var date = new Date(); date.setDate(date.getDate() + days); document.cookie = name + '=' + value + ';expires=' + date; },
removeCookie: function (name) { //設置過期cookie會自動移除 setCookie(name, '1', -1) },
randomColor: function () { return '#' + ('00000' + (Math.random() * 0x1000000 << 0).toString(16)).slice(- 6); },
rendomNum: function (min, max) { return Math.floor(Math.random() * (max - min) + min); },
isPhoneNum: function (str) { return /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/.test(str) },
copy: function (event) {//有選擇性使用 var input = document.createElement('input'); input.type = "text"; input.value = "contain to copy"; event.currentTarget.appendChild(input); input.select(); document.execCommand('copy', false, null); },
initRun: function () {//響應式字體大小 var _this = this, resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize'; _this.fontAdapt(); window.onresize = function () { _this.fontAdapt(); } },
fontAdapt: function () {//div-width(375px)=>(html(20px)=>1rem)==(html(80px)=>html((80/2)px)=2rem) var w = document.documentElement.clientWidth, fz = w * 20 / 375;//375為基準視圖寬度,為設計稿寬度/2; 20為自定義根字體像素大小 document.getElementsByTagName(html)[0].style.fontSize = fz + 'px'; },
getQueryString: function (key) { //正則獲取url後面的參數值'?service=&name=name'=>name const reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)"); const result = window.location.search.substr(1).match