简单的 基于seajs一个base基础库
define(function(require,exports,module){ var base = {}; var isIE_v=(function(){ if (!!(window.attachEvent && navigator.userAgent.indexOf('Opera') === -1)) { return true;} else{return false; }; }()); base.isIE = isIE_v; //浏览器 宽度与高度 base.getBrowserWindowSize = (function () { var de = document.documentElement; return { width: window.innerWidth ||(de&&de.clientWidth) || document.body.clientWidth, height: window.innerHeight || (de && de.clientWidth) || document.body.clientWidth } } ()); base.$=function(){ var elements=[], element; for (var i = 0,max=arguments.length; i < max; i++) { if (typeof arguments[i] === 'string') { element = document.getElementById(arguments[i]); } else { element = arguments[i]; } if (max==1) { return element}else{ elements.push(element)}; }; return elements; }; //得到节点下的第一个元素子节点 如没有返回null base.getFirstElementNode = function (node) { if (!(node = base.$(node))) { return false }; if (node.children.length > 0) { if (node.firstElementChild) { return node.firstElementChild; } else { return node.firstChild; } } else { return null; } }; //得到节点下的最后一个子节点 如没有返回null base.getLastElementNode=function(node){ if (!(node=base.$(node))) { return false}; if(node.children.length>0){ if (node.lastElementChild) { return node.lastElementChild; } else{ return node.lastChild; } } else{ return null; } }; //得到节点下面的直接元素子节点集合(第一层) base.getElementsNode=function(parentnode){ if(!(parentnode=base.$(parentnode))){return false;} return parentnode.children; }; //获得元素节点的下一个节点 如果为最后一个返回null base.getNextElementNode=function(node){ if (!(node = base.$(node))) { return false; }; var lastnode=base.getLastElementNode(node.parentNode); if(lastnode!=node){ if(node.nextElementSibling){ return node.nextElementSibling; } else{ return node.nextSibling; } } else{ return null; } }; //获得元素节点的上一个节点 如果节点为第一个则返回null base.getPreElementNode=function(node){ if (!(node = base.$(node))) { return false; } var firstnode=base.getFirstElementNode(node.parentNode); if(firstnode!=node){ if(node.previousElementSibling){ return node.previousElementSibling; } else{ return node.previousSibling; } } else{ return null; } }; //新元素插入指定元素后面 base.insertAfter = function (newnode, node) { if (!(newnode = base.$(newnode)) || !(node = base.$(node))) { return false; } var parent = node.parentNode; if (base.getLastElementNode(parent) == node) { parent.appendChild(newnode); } else { parent.insertBefore(newnode, base.getNextElementNode(node)); } }; //添加元素到第一个子节点 base.prependChild = function (newnode,parent) { if (!(newnode = base.$(newnode)) || !(parent = base.$(parent))) { return false; } var firstElementNode = base.getFirstElementNode(parent); if (firstElementNode) { parent.insertBefore(newnode, firstElementNode); } else { parent.appendChild(newnode); } }; //删除元素的所有子节点 base.removeChildRen = function (parent) { if (!(parent = base.$(parent))) { return false; } while (parent.firstChild) { parent.firstChild.parentNode.removeChild(parent.firstChild); } return parent; }; //得到元素的文本节点 base.getElementText = function (node) { var t = ""; var node = node.childNodes || node; var length = node.length; for (var i = 0; i < length; i++) { t += node[i].nodeType != 1 ? node[i].nodeValue : getElementText(node[i].childNodes); } return t; } //创建元素 base.createElement = function (tagname, attr) { var element = null; if (typeof tagname === "string") { element = document.createElement(tagname); var key, keyattr; for (key in attr) { key = key.toLowerCase(); if (key == "styles" && typeof attr[key] === "object") { for (keyattr in attr[key]) { element.style[keyattr] = attr[key][keyattr]; if (keyattr == "opacity") { base.setOpacity(element, attr[key][keyattr]); } } } else if (key == "classname" && typeof attr[key] === "string") { base.addClass(element, attr[key]); } else { if (key == "id" && typeof attr[key] === "string") { element.setAttribute("id", attr[key]); } else { element.setAttribute(key, attr[key]); } } } } return element; } //元素可见性切换 base.toggleDisplay=function(node,value){ if (!(node = base.$(node))) { return false; }; if (node.style.display!='none') { node.style.display='none'; } else{ node.style.display=value||''; } return true; }; base.hasClass = function (el,classname) { if (!(el = base.$(el))) { return false; } var aelclassname = base.stringToArray(el.className), aclassname = base.stringToArray(classname), length = aclassname.length, re = true; for (var i = 0; i < length; i++) { if (!aelclassname.contains(aclassname[i])) { re = false; } } return re; } base.addClass = function (el,classname) { if (!(el = base.$(el))) { return false; } var aelclassname = base.stringToArray(el.className), aclassname = base.stringToArray(classname); el.className = base.array.union(aelclassname, aclassname).join(' '); return el; } base.removeClass = function (el, classname) { if (!(el = base.$(el))) { return false; } var aelclassname = base.stringToArray(el.className), aclassname = base.stringToArray(classname); el.className = base.array.minus(aelclassname, aclassname).join(' '); return el; } //根据class获得元素 base.getElementsByClassName = function (classname, parentnode, tagname) { var s = (parentnode || document).getElementsByTagName(tagname || "*"), classarr = base.FormatString(classname).split(' '), classlength = classarr.length; return function () { var a = [], lenght = s.length; for (var i = 0; i < lenght; i++) { if (!s[i].className) { continue; }; if (base.hasClass(s[i], classname)) { a.push(s[i]); } } return a; }(); }; //class切换 单个类 base.toggleClass = function (node, classname) { if (!(node = base.$(node))) { return false; } var classname = base.trim(classname); if (base.hasClass(node, classname)) { base.removeClass(node, classname); } else { base.addClass(node, classname); } } //设置元素的透明度 base.setOpacity=function(node,level){ if(!(node=base.$(node))){ return false;} if(base.isIE){ node.style.filter="alpha(opacity="+level+")"; } else{ node.style.opacity=level/100; } }; //获取元素的样式 base.getStyle=function(node,stylename){ if(!(node=base.$(node))) {return false;} if (node.currentStyle) { return node.currentStyle[stylename]; } else{ return node.ownerDocument.defaultView.getComputedStyle(node,null)[stylename]; } } //去除字符串两边的空白 base.trim = function (str) { return base.isString(str)===true?str.replace(/(^\s*)|(\s*$)/g, ""):false; }; //去除字符串左边的空白 base.Ltrim = function (str) { return base.isString(str) === true ? str.replace(/(^\s*)/g, "") : false; }; //去除字符串右边的空白 base.Rtrim = function (str) { return base.isString(str) === true ? str.replace(/(\s*$)/g, "") : false; }; //字符串中的多个空白替换为单个空白 base.Ctrim = function (str) { return base.isString(str) === true ? str.replace(/\s+/g, ' ') : false; } base.FormatString = function (str) { if (base.isString(str)) { return base.Ctrim(base.trim(str)); } else { return false;} } //字符串转换数组 base.stringToArray = function (str, s) { var s = s || ' '; return base.FormatString(str).split(s); } //字符串重复 base.repeatString = function (str, num) { var temp = ''; for (var i = 0; i < num; i++) { temp += str; } return temp; } //检查输入的字符串 base.isNumber=function(str){ return Object.prototype.toString.call(str)==="[object Number]"; }; base.isString=function(str){ return Object.prototype.toString.call(str) === "[object String]"; }; base.isBoolean=function(str){ return Object.prototype.toString.call(str) === "[object Boolean]"; }; base.isObject = function (str) { return Object.prototype.toString.call(str) === "[object Object]"; } base.isArray = function (str) { return Object.prototype.toString.call(str) === "[object Array]" && Array.isArray(str); }; base.isFunction=function(obj){ return Object.prototype.toString.call(obj) === "[object Function]"; }; base.isNull = function () { return str === null; }; base.isEmpty=function(str){ return /^\s*$/.test(str); }; base.isUndefined=function(str){ return typeof str === "undefined"; }; base.addEvent = function (node, type, fn) { if(!(node=base.$(node))){return false;} if (base.isIE) { node.attachEvent('on'+type,fn); } else if(document.addEventListener){ node.addEventListener(type, fn, false); } else{ node['on'+type]=fn; } }; base.removeEvent = function (node, type, fn) { if (!(node = base.$(node))) { return false; } if (base.isIE) { node.detachEvent('on'+type,fn); } else if(document.addEventListener){ node.removeEventListener(type,fn,false); } else{ node['on'+type]=null; } }; //获得事件对象 base.getEventObject = function (event) { return event || window.event; } //取消事件的默认事件 base.preventDefault = function (event) { var ev = event || base.getEventObject(event); if (ev.preventDefault) { ev.preventDefault(); } else { ev.returnValue = false; } } //得到事件目标对象 base.getEventTarget=function(e){ var ev = e || base.getEventObject(e); var target = e.target || e.srcElement; //safari if (target.nodeType == 3) { target = target.parentNode; } }; //取消冒泡事件 base.stopPropagation = function (e) { var ev = e || base.getEventObject(e); if (base.isIE) { ev.cancelBulle = true; } else{ ev.stopPropagation(); }; }; //得到鼠标按键 base.getMouseButton = function (event) { var ev = event || base.getEventObject(event); var buttons = { 'left': false, 'middle': false, 'right': false }; if (ev.toString() && ev.toString().indexOf("MouseEvent") != -1) { switch (ev.button) { case 0: buttons.left = true; break; case 1: buttons.middle = true; break; case 2: buttons.right = true; break; default: break; } } else if (ev.button) { switch (ev.button) { case 1: buttons.left = true; break; case 2: buttons.right = true; break; case 3: buttons.left = true; buttons.right = true; break; case 4: buttons.middle = true; break; case 5: buttons.left = true; buttons.middle = true; break; case 6: buttons.middle = true; buttons.right = true; break; case 7: buttons.left = true; buttons.middle = true; buttons.right = true; break; default: break; } } else { return false; } return buttons; } //得到鼠标的位置 相对于文档原点 base.getMousePointPositionInDocument = function (event) { var ev = event || base.getEventObject(event); var x = ev.pageX || ev.clientX + (document.body.scrollLeft || document.documentElement.scrollLeft); var y = ev.pageY || ev.clientY + (document.body.scrollTop || document.documentElement.scrollTop); return { 'x': x, 'y':y } } //得到键盘按键信息 base.getKeyPress = function (event) { var ev = event || base.getEventObject(event); var code = ev.keyCode; var value = String.fromCharCode(code); return { 'code': code, 'value': value }; } //得到url的参数 base.getQueryString = function (name) { var reg = new RegExp("(^|&)" + name + "=([^&*])(&|$)","i"); var r = window.location.search.substr(1).match(reg); if (r != null) { return unescape(r[2]); } else { return null; } }//基本的cookie操作 base.cookie = { read: function (name) { var cookieStr = ";" + document.cookie + ";"; var index = cookieStr.indexOf("; " + name + "="); if (index != -1) { var s = cookieStr.substring(index + name.length + 3, cookieStr.length); return unescape(s.substring(0, s.indexOf("; "))); } else { return null; } }, set: function (name, value, expires) { var expDays = expires * 24 * 60 * 60 * 1000; var expDate = new Date(); expDate.setTime(expDate.getTime() + expDays); var expString = expires ? "; expires=" + expDate.toGMTString() : ""; var pathString = ";path=/"; document.cookie = name + "=" + escape(value) + expString + pathString; }, del: function (name) { var exp = new Date(new Date().getTime() - 1); var s = this.read(name); if (s != null) { document.cookie = name + "=" + s + ";expires = " + exp.toGMTString() + ";path=/" } } } //数组的遍历 base.forEach = (function () { //数组与伪数组的遍历 context var _Array_forEach = function (array, block, context) { if (array == null) return; //对String进行特殊处理 if (base.isString(array)) { array = array.split(''); } var i = 0, length = array.length; for (; i < length && block.call(context, array[i], (i + 1), array) !== false; i++) { } }; //对象的遍历 var _Function_forEach = function (object, block, context) { for (var key in object) { //只遍历本地属性 if (object.hasOwnProperty(key) && block.call(context, object[key], key, object) === false) { break; } } }; return function (object, block, context) { if (object == null) return; if (base.isNumber(object.length)) { _Array_forEach(object, block, context); } else { _Function_forEach(object, block, context); } }; })() //两个数组的操作 基于第一个数组 base.array = { //两个数组的交集 intersect: function (a, b) { return a.uniquelize().each(function (o) { return b.contains(o) ? o : null; }); }, //两个数组的差集 minus: function (a,b) { return a.uniquelize().each(function (o) { return b.contains(o) ? null : o; }) }, //两个数组的并集 union: function (a, b) { return a.concat(b).uniquelize(); }, //两个数组的补集 complement: function (a,b) { return this.minus(this.union(a, b), this.intersect(a, b)); } } //对原型的扩展 Array.prototype.contains = function (el) { return RegExp("\\b" + el + "\\b").test(this); } Array.prototype.each = function (fn) { var arr = []; var args = Array.prototype.slice.call(arguments, 1); var length = this.length; for (var i = 0; i < length; i++) { var erg = fn.apply(this, [this[i], i].concat(args)); if (erg != null) { arr.push(this[i]); } } return arr; } Array.prototype.uniquelize = function () { var newarr = []; var length = this.length; for (var i = 0; i < length; i++) { if (!newarr.contains(this[i])) { newarr.push(this[i]); } } return newarr; } module.exports=base; })
以前写的一些方法集合 初步用seajs来进行模块化开发 考虑最多的 是兼容性的问题 . 只是一些方法的堆积,没有模式,感觉最简单的一个了. 学到兼容性的问题 也是一个进步.