前言 該筆記只是為了記錄以前開發使用的方式。 處理命名空間namespace extend及base命名下的常用方法 base下的DOM操作 base下的event事件 base下的array數組 base下的string字元串 base下的cookie操作 base下的date日期操作 base下 ...
前言
該筆記只是為了記錄以前開發使用的方式。
處理命名空間namespace
/** * 處理命名空間 * @param {string} 空間名稱,可多個 * @return {object} 對象 */ var namespace = function(){ var argus = arguments, argusLen = argus.length; for(var i =0; i < argusLen; i++){ var objs = argus[i].split('.'), objsLen = objs.length, obj = window; for(var j = 0; j < objsLen; j++){ obj[objs[j]] = obj[objs[j]] || {}; obj = obj[objs[j]]; } } return obj; } namespace("base");
extend及base命名下的常用方法
(function(){ /** * 獲取對象類型 * @private 私有方法 * @param {object} object 對象 * @return {string} 類型 * 可判斷類型:Boolean Number String Function Array Date RegExp Object */ function getParamType(obj){ return obj == null ? String(obj) : Object.prototype.toString.call(obj).replace(/\[object\s+(\w+)\]/i,"$1") || "object"; }; /** * 為對象進行擴展屬性和方法 * @param {object} object 對象 * @return {bool} 是/否 */ base.extend = function(destination, source) { if (destination == null) { destination = source; }else { for (var property in source){ if ( getParamType(source[property]).toLowerCase() === "object" && getParamType(destination[property]).toLowerCase() === "object" ){ extend(destination[property], source[property]); }else{ destination[property] = source[property]; } } } return destination; } base.extendLess = function(destination, source) { var newopt = source; for (var i in destination) { if (isObject(source) && typeof(source[i]) != 'undefined') { destination[i] = newopt[i] } } return destination } /** * 類式繼承類 * @param {object} subClass 子類 * @param {object} superClass 基礎類 * @return {undefined} */ base.extendClass = function(subClass,superClass){ var F = function(){}; F.prototype = superClass.prototype; subClass.prototype = new F(); subClass.prototype.constructor = subClass; subClass.superclass = superClass.prototype; if (superClass.prototype.constructor == Object.prototype.constructor){ superClass.prototype.constructor = superClass } } /** * 原型繼承類 * @param {object} object 基類 * @return {object} 生成的子類 */ base.cloneClass = function(object){ if(!isObject(object)) return object; if(object == null) return object; var F = new Object(); for(var i in object) F[i] = cloneClass(object[i]); return F; } /** * 綁定上下文 * @param {function,context} object * @return {object} */ base.bind = function(fn,context){ return function(){ return fn.apply(context,arguments); }; } base.extend( base, { /** * 判斷對象是否定義 * 其實只對對象中的元素判斷有效,如是純變數,此方法會無法調用,需要外面加try * @param {object} object 對象 * @return {bool} 是/否 */ isUndefined : function(o){ return o === undefined && typeof o == "undefined"; }, /** * 判斷對象是否數組 * @param {object} object 對象 * @return {bool} 是/否 */ isArray : function(obj) { return getParamType(obj).toLowerCase() === "array"; }, /** * 判斷對象是否函數 * @param {object} object 對象 * @return {bool} 是/否 */ isFunction : function(obj){ return getParamType(obj).toLowerCase() === "function"; }, /** * 判斷對象是否對象 * @param {object} object 對象 * @return {bool} 是/否 */ isObject : function(obj) { return getParamType(obj).toLowerCase() === "object"; }, /** * 判斷對象是否數值 * @param {object} object 對象 * @return {bool} 是/否 */ isNumber : function(obj) { return getParamType(obj).toLowerCase() === "number"; }, /** * 判斷對象是否字元串 * @param {object} object 對象 * @return {bool} 是/否 */ isString : function(obj) { return getParamType(obj).toLowerCase() === "string"; }, /** * 判斷是否布爾值 * @param {object} object 對象 * @return {bool} 是/否 */ isBoolean : function(obj) { return getParamType(obj).toLowerCase() === "boolean"; }, /** * 判斷對象是否日期 * @param {object} object 對象 * @return {bool} 是/否 */ isDate : function(obj){ return getParamType(obj).toLowerCase() === "date"; }, /** * 判斷對象是否DOM元素 * @param {object} obj DOM對象 * @return {bool} 是/否 */ isDom : function(obj){ try{ return obj && typeof obj === "object" && !isUndefined(obj.nodeType) && obj.nodeType==1 && !isUndefined(obj.nodeName) && typeof obj.nodeName == "string"; } catch(e){ //console.log(e) return false; } }, /** * 獲取DOM對象的值 * @param {object} obj DOM對象 * @return {string} 取value或innerHTML */ getDomVal : function(obj){ return obj.value || obj.innerHTML; }, /** * 索引序列 * @param {serial,function} 數組或對象集合 * @return {undefined} */ forEach : function(haystack, callback) { var i = 0, length = haystack.length, name; if (length !== undefined) { for (; i < length;) { if (callback.call(haystack[i], i, haystack[i++]) === false) { break; } } } else { for (name in haystack) { callback.call(haystack[name], name, haystack[name]); } } }, /** * 獲取dom對象 * @param {string|dom} dom的id或對象k * @return {dom} */ g : function(obj){ return (typeof obj=='object')?obj:document.getElementById(obj); } }); })(); base.extend(window, base);
base下的DOM操作
namespace("base.dom"); (function(){ var dom = base.dom; var userAgent = navigator.userAgent.toLowerCase(); extend( dom, { /** * 判斷瀏覽器類型 */ browser : { /** * 獲取版本號 */ version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1], /** * 是否webkit瀏覽器 */ webkit: /webkit/.test( userAgent ), /** * 是否opera瀏覽器 */ opera: /opera/.test( userAgent ), /** * 是否IE瀏覽器 */ msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ), /** * 是否mozilla瀏覽器 */ mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent ), /** * 是否TT瀏覽器 */ tt: /tencenttraveler/.test( userAgent ), /** * 是否chrome瀏覽器 */ chrome: /chrome/.test( userAgent ), /** * 是否firefox瀏覽器 */ firefox: /firefox/.test( userAgent ), /** * 是否safari瀏覽器 */ safari: /safari/.test( userAgent ), /** * 是否gecko瀏覽器 */ gecko: /gecko/.test( userAgent ), /** * 是否IE6 */ ie6: this.msie && this.version.substr(0,1) == '6' }, /** * 獲取dom對象 * @param {string|dom} dom的id或對象 * @return {dom} */ g : function(obj){ return (typeof obj=='object')?obj:document.getElementById(obj); }, /** * 判斷DOM對象是否存在樣式類名稱 * @param {dom} element dom對象 * @param {string} className 樣式名稱 * @return {bool} */ hasClassName : function(element, className) { var elementClassName = element.className; return (elementClassName.length > 0 && (elementClassName == className || new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName))); }, /** * 為DOM對象增加樣式類名稱 * @param {dom} element dom對象 * @param {string} className 樣式名稱 * @return {dom} */ addClassName : function(element, className) { if (!base.hasClassName(element, className)) element.className += (element.className ? ' ' : '') + className; return element; }, /** * 為DOM對象刪除樣式類名稱 * @param {dom} element dom對象 * @param {string} className 樣式名稱 * @return {dom} */ removeClassName : function(element, className) { element.className = base.trim(element.className.replace( new RegExp("(^|\\s+)" + className + "(\\s+|$)") , ' ')); return element; }, /** * 為dom對象設置樣式 * @param {dom} ele dom對象 * @param {object} styles 樣式對象 like:{width:100,height:100} * @return undefined */ setStyle: function(ele, styles){ for (var i in styles) { ele.style[i] = styles[i]; } }, /** * 為dom對象獲取選定屬性的樣式 * @param {dom} ele dom對象 * @param {string} prop 屬性名稱 * @return 屬性樣式 */ getStyle: function(el, prop){ var viewCSS = isFunction(document.defaultView) //(typeof document.defaultView == 'function') ? document.defaultView() : document.defaultView; if (viewCSS && viewCSS.getComputedStyle) { var s = viewCSS.getComputedStyle(el, null); return s && s.getPropertyValue(prop); } return (el.currentStyle && (el.currentStyle[prop] || null) || null); }, /** * 獲取頁面最大高度 * @return 屬性樣式 */ getMaxH: function(){ return (this.getPageHeight() > this.getWinHeight() ? this.getPageHeight() : this.getWinHeight()) }, /** * 獲取頁面最大寬度 * @return 屬性樣式 */ getMaxW: function(){ return (this.getPageWidth() > this.getWinWidth() ? this.getPageWidth() : this.getWinWidth()) }, /** * 網頁內容高度 * @return {int} 網頁內容高度 */ getPageHeight: function(){ var h = (window.innerHeight && window.scrollMaxY) ? (window.innerHeight + window.scrollMaxY) : (document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight); return h > document.documentElement.scrollHeight ? h : document.documentElement.scrollHeight }, /** * 網頁內容寬度 * @return {int} 網頁內容寬度 */ getPageWidth: function(){ return (window.innerWidth && window.scrollMaxX) ? (window.innerWidth + window.scrollMaxX) : (document.body.scrollWidth > document.body.offsetWidth ? document.body.scrollWidth : document.body.offsetWidth); }, /** * 瀏覽器可視區域高度 * @return {int} 網可視區域高度 */ getWinHeight: function(){ return (window.innerHeight) ? window.innerHeight : (document.documentElement && document.documentElement.clientHeight) ? document.documentElement.clientHeight : document.body.offsetHeight }, /** * 瀏覽器可視區域寬度 * @return {int} 網可視區域寬度 */ getWinWidth: function(){ return (window.innerWidth) ? window.innerWidth : (document.documentElement && document.documentElement.clientWidth) ? document.documentElement.clientWidth : document.body.offsetWidth }, /** * 設置dom透明度 * @param {dom} ele dom對象 * @param {int} level 透明度值(0-100的整數) * @return {undefined} */ setOpacity: function(ele, level){ //level = Math.min(1,Math.max(level,0)); if(this.browser.msie && (!document.documentMode || document.documentMode < 9)){ ele.style.filter = 'Alpha(opacity=' + level + ')' }else{ ele.style.opacity = level / 100 } }, /** * 獲取頁面中對象的絕對X位置 * @param {dom} e dom對象 * @return {int} */ getX: function(e) { var t = e.offsetLeft; while (e = e.offsetParent) t += e.offsetLeft; return t }, /** * 獲取頁面中對象的絕對Y位置 * @param {dom} e dom對象 * @return {int} */ getY: function(e) { var t = e.offsetTop; while (e = e.offsetParent) t += e.offsetTop; return t }, /** * 獲取url中的參數值 * @param {string} pa 參數名稱 * @return {string} 參數值 */ request: function(pa){ var url = window.location.href.replace(/#+.*$/, ''), params = url.substring(url.indexOf("?")+1,url.length).split("&"), param = {} ; for (var i=0; i<params.length; i++){ var pos = params[i].indexOf('='),//查找name=value key = params[i].substring(0,pos), val = params[i].substring(pos+1);//提取value param[key] = val; } return (typeof(param[pa])=="undefined") ? "" : param[pa]; } }) })(); base.extend(base, base.dom);
base下的event事件
namespace("base.event"); (function(){ var event = base.event; extend( event, { /** * 停止事件繼續進行 * @param {event} e 事件 * @return {dom} */ preventDefault : function(e){ if (e.preventDefault){ e.preventDefault(); } else{ e.returnValue = false; } }, /** * 阻止事件冒泡傳遞 * @param {event} e 事件 * @return {dom} */ stopPropagation : function(e){ if (e.stopPropagation){ e.stopPropagation(); } else{ e.cancelBubble = true; } }, /** * 為DOM對象增加事件 * @param {dom} element dom對象 * @param {string} type 事件名稱 * @param {function} type 事件方法 * @return {undefined} */ addEvent : function(el, type, fn){ if (window.addEventListener){ el['e'+type+fn] = fn; el[type+fn] = function(e){ var _e = e || window.event, _r = el['e'+type+fn](_e); if (_r==false) { base.preventDefault(_e); base.stopPropagation(_e); } } el.addEventListener(type, el[type+fn], false); } else if (window.attachEvent){ el['e'+type+fn] = fn; el[type+fn] = function(e){ var _r = el['e'+type+fn](window.event); if (_r==false) base.preventDefault(window.event); } el.attachEvent( 'on'+type, el[type+fn] ); return; } else{ el['on' + type] = fn; } }, /** * 為DOM對象移除事件 * @param {dom} element dom對象 * @param {string} type 事件名稱 * @param {function} type 事件方法 * @return {undefined} */ removeEvent : function (el, type, fn){ if (window.removeEventListener){ el.removeEventListener(type, el[type+fn], false); el[type+fn] = null; } else if (window.detachEvent){ el.detachEvent( 'on'+type, el[type+fn] ); el[type+fn] = null; return; } else{ el['on' + type] = null; } }, isReady : false, readyFn : [], /** * dom ready事件 * @param {dom} element dom對象 * @param {string} type 事件名稱 * @param {function} type 事件方法 * @return {undefined} */ ready : function (fn){ bindReadyEvent(); if ( base.isReady ){ fn.call(); } else { if (isFunction(fn)){ base.readyFn.push(fn); } } } }); function bindReadyEvent(){ if(document.readyState === 'complete'){ return ready(); } if(document.addEventListener){ document.addEventListener("DOMContentLoaded", function(){ document.removeEventListener("DOMContentLoaded", arguments.callee, false); ready(); },false); window.addEventListener("load", ready, false); } else if(document.attachEvent){ document.attachEvent("onreadystatechange", function(){ if (document.readyState === "complete"){ document.detachEvent("onreadystatechange", arguments.callee); ready(); } }); window.attachEvent("onload",ready); if(document.documentElement.doScroll && window == window.top){ if(base.isReady) return; try{ document.documentElement.doScroll("left"); }catch(e){ setTimeout(arguments.callee, 0); return; } ready(); } } } function ready(){ if(!base.isReady){ if(!document.body){ return setTimeout(ready,13); } base.isReady = true; if(base.readyFn.length >0){ var i=0,fn; while(fn = base.readyFn[i++]) fn.call(); base.readyFn.length = 0; } } } })(); base.extend(base, base.event);
base下的array數組
namespace("base.array"); (function(){ var array = base.array; extend( array, { /** * 判斷數組內容個數 * @param {array} array 對象 * @return {int} 長度 */ getLength : function(arr){ var l = 0; for(var key in arr){ l ++; } return l; }, /** * 複製數組 * @param {array} array 對象 * @return {array} 新數組對象 */ clone : function(arr){ var a = []; for(var i=0; i<arr.length; ++i) { a.push(arr[i]); } return a; }, /** * 判斷數組中是否存在這個值 * @param {array} arr 數組對象 * @param {object} value 對象 * @return {bool} 是/否 */ hasValue : function(arr, value){ var find = false; if (isArray(arr) || isObject(arr)) for(var key in arr){ if (arr[key] == value) find = true; } return find; }, /** * 根據值獲得數組中的key * @param {array} arr 數組對象 * @param {object} value 對象 * @return {string} key */ getArrayKey : function(arr, value){ var findKey = -1; if (isArray(arr) || isObject(arr)) for(var key in arr){ if (arr[key] == value) findKey = key; } return findKey; }, /** * 返回a1數組有a2沒有的值 * @param {array} a1 數組對象 * @param {array} a2 數組對象 * @return {array} key */ filter : function (a1, a2) { var res = []; for(var i=0;i<a1.length;i++) { if(!base.hasValue(a2, a1[i])) res.push(a1[i]); } return res; }, /** * 兩個數組的值的交集 * @param {array} arr 數組 * @param {array} arr 數組 * @return {array} key */ unique : function (a1, a2) { return base.filter(a1,a2).concat(base.filter(a2,a1)) } }); })(); base.extend(base, base.array);
base下的string字元串
namespace("base.string"); (function(){ var string = base.string; extend( string, { /** * 查找字元串的位元組長度<br/> * 中文算2 英文算1<br/> * @param {string} str 字元串 * @return {int} */ getByteLength : function(str){ var bytes=0,i=0; for (; i<str.length; ++i,++bytes) { if ( str.charCodeAt(i) > 255 ) { ++bytes; } } return bytes; }, /** * 查找有多少個雙位元組字元 * @param {string} str 字元串 * @return {int} */ getDwordNum : function(str){ return string.getByteLength(str) - str.length; }, /** * 查找有多少個漢字字元 * @param {string} str 字元串 * @return {int} */ getChineseNum : function(str){ return str.length - str.replace(/[\u4e00-\u9fa5]/g,"").length; }, /** * 截取中文字元串<br/> * 取iMaxBytes 或最後一個中文字元出現的地方替換字元<br/> * @param {string} str 字元串 * @param {int} iMaxBytes 字元串 * @param {string} sSuffix 替補字元串 * @return {string} */ cutChinese : function(str, iMaxBytes, sSuffix){ if(isNaN(iMaxBytes)) return str; if(string.getByteLength(str)<=iMaxBytes) return str; var i=0, bytes=0; for (; i<str.length && bytes<iMaxBytes; ++i,++bytes) { if ( str.charCodeAt(i) > 255 ) { ++bytes; } } sSuffix = sSuffix || ""; return (bytes-iMaxBytes == 1 ? str.substr(0,i-1) : str.substr(0,i) ) + sSuffix; }, /** * 去掉字元串左邊的非空字元 * @param {string} str 字元串 * @return {string} */ trimLeft : function(str){ return str.replace(/^\s+/,""); }, /** * 去掉字元串右邊的非空字元 * @param {string} str 字元串 * @return {string} */ trimRight : function(str){ return str.replace(/\s+$/,""); }, /** * 去掉字元串左右兩邊的非空字元 * @param {string} str 字元串 * @return {string} */ trim : function(str){ return base.trimRight(base.trimLeft(str)); }, /** * 成對字元串替換 * @param {string} str 字元串 * @param {array} str 字元串<br/> array包含兩個 [0] 查找內容,[1] 替換內容<br/> array可以出現多次<br/> * @return {string} */ replacePairs : function(){ var str = arguments[0]; for (var i=1; i<arguments.length; ++i) { var re = new RegExp(arguments[i][0], "g"); str = str.replace(re, arguments[i][1]); } return str; }, /** * 字元串替換為HTML編碼形式 * @param {string} str 字元串 * @return {string} */ toHtml : function(str){ var CONVERT_ARRAY = [ ["&", "&"], [" ", " "], ["'", "'"], ["\"", """], ["/", "/"], ["<", "<"], [">", ">"], ["\\\\", "\"], ["\n", "<br />"], ["\r", ""] ]; return base.replacePairs.apply(this, [str].concat(CONVERT_ARRAY)); }, /** * 校驗郵箱地址 * @param {string} str 字元串 * @return {bool} */ isMail : function(str){ return /^(?:[\w-]+\.?)*[\w-]+@(?:[\w-]+\.)+[\w]{2,3}$/.test(str); }, /** * 校驗普通電話、傳真號碼:可以“+”開頭,除數字外,可含有“-” * @param {string} str 字元串 * @return {bool} */ isTel : function(str){ return /^[+]{0,1}(\d){1,3}[ ]?([-]?((\d)|[ ]){1,12})+$/.test(str); }, /** * 校驗手機號碼:必須以數字開頭 * @param {string} str 字元串 * @return {bool} */ isMobile : function(str){ return /^1[34578]\d{9}$/.test(str); }, /** * 校驗郵政編碼 * @param {string} str 字元串 * @return {bool} */ isZipCode : function(str){ return /^(\d){6}$/.test(str); }, /** * 是否身份證號碼 * @param {string} str 字元串 * @return {bool} */ isIDCard : function(str){ var C15ToC18 = function(c15) { var cId=c15.substring(0,6)+"19"+c15.substring(6,15); var strJiaoYan =[ "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"]; var intQuan =[7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; var intTemp=0; for(i = 0; i < cId.length ; i++) intTemp += cId.substring(i, i + 1) * intQuan[i]; intTemp %= 11; cId+=strJiaoYan[intTemp]; return cId; } var Is18IDCard = function(IDNum) { var aCity={11:"北京",12:"天津",13:"河北",14:"山西",15:"內蒙古",21:"遼寧",22:"吉林",23:"黑龍江",31:"上海",32:"江蘇",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山東",41:"河南",42:"湖北",43:"湖南",44:"廣東",45:"廣西",46:"海南",50:"重慶",51:"四川",52:"貴州",53:"雲南",54:"西藏",61:"陝西",62:"甘肅",63:"青海",64:"寧夏",65:"新疆",71:"臺灣",81:"香港",82:"澳門",91:"國外"}; var iSum=0, info="", sID=IDNum; if(!/^\d{17}(\d|x)$/i.test(sID)) { return false; } sID=sID.replace(/x$/i,"a"); if(aCity[parseInt(sID.substr(0,2))]==null) { return false; } var sBirthday=sID.substr(6,4)+"-"+Number(sID.substr(10,2))+"-"+Number(sID.substr(12,2)); var d=new Date(sBirthday.replace(/-/g,"/")) if(sBirthday!=(d.getFullYear()+"-"+ (d.getMonth()+1) + "-" + d.getDate()))return false; for(var i = 17;i>=0;i --) iSum += (Math.pow(2,i) % 11) * parseInt(sID.charAt(17 - i),11) if(iSum%11!=1)return false; return true; } return str.length==15 ? Is18IDCard(C15ToC18(str)) : Is18IDCard(str); }, /** * 是否全部是中文 * @param {string} str 字元串 * @return {bool} */ isChinese : function(str){ return base.getChineseNum(str)==str.length ? true