代码非原创,是收集的一些网上的代码。本着好东西齐分享的原则和大家一起共享一下,如若涉及代码著作权请@我。
(function(win){ var base=win['base']||{}; base={ $:function(id){//获取id元素 return document.getElementById(id); }, accordion:function(obj, step, num, type){ if(obj.timer){ clearInterval(obj.timer); } obj.timer=setInterval(function(){ base.accordion(obj, step, num, type); }); var curWidth=type=='width'?obj.clientWidth:obj.clientHeight; if(curWidth===num){ clearInterval(obj.timer); obj.timer=null; }else{ obj.style[type]=curWidth+step+'px' } }, addClass:function(node, className){//添加class if(!this.hasClass(node, className)){ node.ClassName=node.className+' '+className; } }, addCss:function(url, fn){//添加css文件 var link=document.createElement('link'); link.href=url; link.type='test/css'; link.rel='stylesheet' this.onload(link, fn); document.getElementsByTagName('head')[0].appendChild(link); }, addEvent:function(node, type, fn){//添加事件函数 if(node.addEventListener){ node.addEventListener(type, fn, false); }else if(node.attachEvent){ node.attachEvent('on'+type, fn); }else{ node['on'+type]=fn; } }, ajax:function(opts){//异步加载事件 var dataType=opts.dataType.toLocaleLowerCase(); opts.data=decodeURIComponent(typeof opts.data==='undefind'?'':typeof opts.data==='object'?this.obj2str(opts.data):opts.data); if(dataType==='jsonp'){ var fnName='jsonp_'+Math.floor(Math.random()*10E10)+'_'+new Date().getTime(); opts.url=opts.url+'?callback='+fnName+'&'+opts.data+'&'+'r='+new Date()+getTime(); var script=this.addScript(opts.url, null); win[fnName]=function(data){ opts.sucFn&&opts.sucFn(data); doc.getElementsByTagName('head')[0].removeChild(script); } }else{ var req=win.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject('Microsoft.XMLHTTP'); if(opts.type&&opts.type.toLowerCase()==='post'){ req.setRequsetHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8'); }else{ opts.url=opts.url+'?'+opts.data; } req.open(opts.type, opts.url, true); req.send(opts.data); req.onreadystatechange=function(){ if(req.readyState==4){ if(req.status===200){ opts.sucFn&&opts.sucFn(dataType==='json'?X.parseJSON(req.responseText):req.responseText); }else{ opts.failFn&&opts.failFn(req.status); } } } } }, append:function(node, parent){//添加子元素 if(typeof node==='object'){ parent.appendChild(node); }else{ var fragment=document.createDocumentFragment(); fragment.innerHTML=node; parent.appendChild(fragment); } }, attr:function(element, attrName, attrVal){//获取或设置元素属性 if(arguments.length==2&&typeof attrName==='string'){ return element.getAttribute(attrName); }else{ var attr={}; if(typeof attrName==='string'){ attr[attrName]=attrVal; }else{ attr=attrName; } for(var n in attr){ element.setAttribute(n, attr[n]); } } return element; }, clone:function(obj){//深度克隆 var newObj; if(typeof obj==='object'){ if(Object.prototype.toString.call(obj)==='object Array'){ newObj=[]; var i=obj.length; while(i--){ newObj[i]=base.clone(obj[i]); } return newObj; }else{ newObj={}; for(var j in obj){ newObj[i]=base.clone(obj[j]); } } }else{ return obj; } return newObj; }, css:function(node, attr){//获取样式属性 if(attr!='opacity'){ return parseInt(node.currentStyle?node.currentStyle[attr]:doc.defaultView.getComputedStyle(node, false)[attr]) }else{ return Math.round(100*parseFloat(node.currentStyle?node.currentStyle[attr]:document.defaultView.getComputedStyle(node,false)[attr])) } }, delEvent:function(node, type, fn){//移除事件函数 if(node.removeEventListener){ node.removeEventListener(type, fn, false); }else if(node.detachEvent){ node.detachEvent('on'+type, fn); }else{ node['on'+type]=null; } }, dir:function(data){ try{ console.dir(data); }catch(ex){} }, each:function(fn){ for(var i=0; i<this.length; i++){ if(fn&&fn.call(this[i], i)===false){ break; } } }, extend:function(target, options){//继承target对象属性 for(var name in options){ var copy=options[name]; if(target===copy){ continue; } if(copy!==undefined){ target[name]=copy; } } return target; }, fadeIn:function(obj){ if(obj.timer){ clearInterval(obj.timer); } obj.timer=setInterval(function(){ base.fadeIn(obj); },100); if(!win['xcxFadeInOptacity']){ win['xcxFageInOptacity']=0; obj.style.display=''; } win['xcxFadeInOpacity']+=0.1; obj.style.opacity=win['xcxFadeInOpacity']+''; if(win['xcxFadeInOpacity']>=1){ win['xcxFadeInOpacity']=0; clearInterval(obj.timer); } }, fadeOut:function(obj){ if(obj.timer){ clearInterval(obj.timer); } obj.timer=setInterval(function(){ base.fadeOut(obj); }); if(!win['xcxFadeOutOpacity']){ win['xcxFadeOutOpacity']=1; } win['xcxFadOutOpacity']-=0.1; obj.style.opacity=win['xcxFadeOutOpacity']+''; if(win['xcxFadeOutOpacity']<=0){ obj.style.display='none'; win['xcxFadeOutOpacity']=1; clearInterval(obj.timer); } }, filter:function(list, fn){//过滤包含fn函数的对象 var reList=[]; this.each.call(list, function(){ if(fn.call(this)){ reList.push(this); } }); reList.each=function(fn){ base.each.call(reList, fn); } return reList; }, getBrowser:function(){//获取浏览器版本 var bs={}; var u=win.navigator.userAgent.toLocaleLowerCase(), sougou=/se 2.x metasr 1.0/, qqbrowser= /(qqbrowser)\/([\d.]+)/, msie=/(msie) ([\d.]+)/, chrome=/(chrome)\/([\d.]+)/, firefox=/(firefox)\/([\d.]+)/, safari=/(safari)\/([\d.]+)/, opera=/(opera)\/([\d.]+)/, b=u.match(sougou)||u.match(qqbrowser)||u.match(msie)||u.match(chrome)||u.match(firefox)||u.match(safari)||u.match(opera)||[0,0,0]; if(b[1]==='opera'||b[1]==='safari'){ b[2]=u.match(/(version)\/([\d.]+)/)[2]; } if(u.match(sougou)){ b=[]; b[1]='sougo'; b[2]='msie7.0'; } bs[b[1]]=b[2]; bs['name']=b[1]; bs['version']=b[2]; return bs; }, getByAttr:function(attrName, attrVal, parent){//筛选属性值对象 parent=parent||document.body; var list=[]; var elements=parent.getElementsByTagName('*'); for(var i=0; i<elements.length; i++){ var element=elements[i]; var reg=new RegExp(attrVal.replace(/,/g, '|'), 'g'); if(reg.test(element.getAttribute(attrName))){ list.push(element); } } list.each=function(fn){ base.each.call(list, fn); } return list; }, getByClass:function(className, parent){//筛选class值对象 var node=parent||document; var list=[]; if(node.getElementsByClassName){ list=node.getElementsByClassName(className); }else{ var nodes=nodes.getElementsByTagName('*'); for(var i=0; i<nodes.length; i++){ if(this.hasClass(nodes[i], className)){ list.push(nodes[i]); } } } list.each=function(fn){ base.each.call(list, fn); } return list }, getByTag:function(tagName, parent){//筛选标签对象 parent=parent||document.body; var list=[]; var tags=tagName.split(','); for(var i=0, len=tags.length; i<len; i++){ var nl=parent.getElementsByTagName(tags[i]); for(var j=0, jLen=nl.length; j<jLen; j++){ list.push(nl[j]); } } list.each=function(fn){ base.each.call(list, fn); } return list; }, getEventXY:function(e, isEnd){//获取鼠标相对页面位置 e=e||win.event; if(!('ontouchstart' in win)){ return [e['pageX'], e['pageY']]; }else if(isEnd){ return [e.changedTouches[0]['pageX'], e.changedTouches[0]['pageY']] } return [e.touches[0]['pageX'], e.touches[0]['pageY']] }, getOffset:function(obj){//获取元素相对页面位置 var arr=(function(o){ var l=0, t=0; while(o!==null&&o!==document.body){ l+=o.offsetLeft; t+=o.offsetTop; o=o.offsetParent; } return [l, t]; })(obj); arr.push(obj.offsetWidth); arr.push(obj.offsetHeight); return arr; }, getOffset2:function(obj){ var arr=[]; var l=obj.getBoundingClientRect().left + window.document.documentElement.scrollLeft +window.document.body.scrollLeft; var t=obj.getBoundingClientRect().top + window.document.documentElement.scrollTop +window.document.body.scrollTop; arr.push(l); arr.push(t); arr.push(obj.offsetWidth); arr.push(obj.offsetHeight); }, getrQueryStringArgs:function(){//获取url中?后的相关属性值 var qs=(win.location.search.length>0?win.location.search.substring(1):'') var args={}; var items=qs.length?qs.split('&'):[]; var len=items.length; for(var i=0; i<len; i++){ var item=items[i].split('='); var name=decodeURIComponent(item[0]); var value=decodeURIComponent(item[1]); if(name.length){ args[name]=value; } } return args; }, getStyle:function(elem, name){//获取样式属性 if(elem.style[name]){ return elem.style[name]; }else if(elem.currentStyle){// for ie return elem.currentStyle[name]; }else if(document.defaultView&document.defaultView.getComputedStyle){ name=name.replace(/[A-Z]/g, "-$1"); name=name.toLowerCase(); var s=document.defaultView.getComputedStyle(elem, ""); return s&&s.getPropertyValue(name); }else{ return null; } }, hasClass:function(node, className){//判断元素是否包含某一class var names=node.className.split(/\s+/); for(var i=0; i<names.length; i++){ if(names[i]===className){ return true; } } return false; }, hasClass2:function(node, className){ return node.ClassName.match("(^|\\s+)"+classStr+"(\\s|$)"); }, isArray:function(o){ return Object.prototype.toString.call(o)==='[object Array]'; }, isLeapYear:function(y){ var flag=false; if((y%400===0)||(y%100!==0)&&(y%4===0)){ flag=true; } return flag; }, log:function(data){ try{ console.log(data); }catch(ex){} }, obj2str:function(obj){//将对象转换为字符串 var str = []; switch (true) { case typeof obj === 'undefined': str = ''; break; case typeof obj === 'string': str = '\"' + obj.replace(/([\"\\])/g, '\\$1').replace(/(\n)/g, '\\n').replace(/(\r)/g, '\\r').replace(/(\t)/g, '\\t') + '\"'; break; case typeof obj === 'object': if (!this.isArray(obj)) { for (var i in obj) { str.push('\"' + i + '\":' + this.obj2str(obj[i])); } if (!!doc.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(obj.toString)) { str.push('toString:' + obj.toString.toString()); } str = '{' + str.join() + '}'; } else { for (var j = 0; j < obj.length; j++) { str.push(this.obj2str(obj[j])); } str = '[' + str.join() + ']'; } break; default: str = obj.toString().replace(/\"\:/g, '":""'); break; } return str; }, onload:function(obj, fn){ obj.οnlοad=function(){ fn(); } if(this.getBrowser().name==='msie'){ var t=win.setInterval(function(){ if(obj.readyState==='loaded'||obj.readyState==='complete') win.clearInterval(t); fn(); }, 10); } }, parseJSON:function(data){ if(!data||typeof data!=='string'){ return null; } data=this.trim(data); if(win.JSON&&win.JSON.parse){ return win.JSON.parse(data); } return (new Function("return "+data))(); }, preventDefault:function(e){//阻止默认行为 e=e||win.event; if(e.preventDefault){ e.preventDefault(); }else{ e.returnValue=false; } }, query:function(selector, container){//简易选择器 var result=[]; function get(element, index, arr){ element=element?element:document.body; if(!base.isArray(element)){ element=[element]; } if(arr[indx]){ result=[]; var match=/^#(.+)$|^\.(.+)$|^([\w\d]+)$/.exec(arr[index]); if(match[1]){//id选择 result=document.getElementById(match[1]); }else if(match[2]){//class选择 for(var i=0, len=element.length; i<len; i++){ base.getByClass(match[2], element[i]).each(function(){ result.push(this); }); } }else if(match[3]) {//标签选择 for(var j = 0, jLen = element.length; j < jLen; j++) { X.getByTag(match[3], element[j]).each(function() { result.push(this); }); } } index++; get(result, index, arr); } } get(container, 0, selector.split(/\s/)); return result; }, stopPropagation:function(e){//阻止冒泡 if(e.stopPropation){ e.stopPropagation(); }else{ e.cancelBubble=true; } }, swipe:function(obj, sFn, mFn, eFn){ var canMove, xy; this.addEvent(obj, 'touchstart', function(e){ canMove=0; xy=base.getEventXY(e); sFn&&sFn(e, xy[0], xy[1]); }); this.addEvent(obj, 'touchmove', function(e){ var mxy=base.getEventXY(e); if(canMove===0){ if(Math.abs(mxy[0]-xy[0])>Math.abs(mxy[1]-xy[1])){ canMove=1; }else{ canMove=2; return; } } var result=mFn&&mFn(e, xy[0], mxy[0]); if(!result){ e.preventDefault(); e.stopPropagation(); } }); this.addEvent(obj, 'touchend', function(e){ var exy=base.getEventXY(e, 'true'); if(canMove!==2){ eFn&&eFn(e, xy[0], exy[0]); canMove=2; } }); }, touch:function(obj, fn){//touch事件 var duration=0, fixDistance=10, time, xy; this.addEvent(obj, 'touchstart', function(e){ time=new Date().valueOf(); xy=base.getEventXY(e); }); this.addEvent(obj, 'touchend', function(e){ var result=true; var endTime=new Date().valueOf(); var endXY=base.getEventXY(e, true); if(endTime-time>duration&&Math.abs(endXY[0]-xy[0])<fixDistance&&Match.abs(endXY[1]-xy[1])<fixDistance){ result=fn&fn(e); } if(!result){ e.preventDefault(); e.stopPropagation(); } }); }, trim:function(text){ return text==null?'':text.replace(/(^\s*)|(\s*$)/g, ''); } } Array.prototype.distinct=function(){//数组去重 var sameObj=function(a, b){ var tag=true; if(!a||!b){ return false; } for(var x in a){ if(!b[x]){ return false; } if(typeof(a[x])==='object'){ tag=sameObj(a[x], b[x]); }else{ if(a[x]!==b[x]){ return false; } } } return tag; } var newArr=[], obj={}; for(var i=0, len=this.length; i<len; i++){ if(!sameObj(obj[typeof(this[i])+this[i]], this[i])){ newArr.push(this[i]); obj[typeof(this[i])+this[i]]=this[i]; } } return Arr; } })(window);