/** *@star : 2012.2.3 *@version : 1.2.0 */ ~ function(win, doc){ var $ = function(arg){ var c = somobject; switch($.typeof(arg)){ case "object" : return arg.nodetype ? new c([arg]) : new c(arg); //为了区分nodelist和dom对象 case "string" : return new c(selector(arg)); case "array" : return new c(arg); case "function" : return $.dom.ready(arg); default : return []; } }; var html = $.html = doc.documentelement; var head = $.head = doc.head || doc.getelementsbytagname('head')[0]; var body = $.body = doc.body; /*----base----*/ $.browser = (function(){ return { ie6 : !!win.activexobject && !win.xmlhttprequest, ie7 : !+"\v1" && !doc.queryselector, ie8 : !+"\v1", ie : !!win.attachevent && !win.opera, opear : !!win.opera } })(); /** * @fileoverview somesayss core核心 v1.1.0 */ $.class = { creat:function(){ return function(){ this.init.apply(this, arguments); } }, extend:function(current,target,futher){ for(var i in current.prototype){ target.prototype[i] = current.prototype[i] } if(!futher) return; for(var j in futher){ target.prototype[j] = futher[j] } var _currentinit = $.use(current.prototype.init); var _futherinit = $.use(futher.init); var _initargname = _currentinit.argumentsname().concat(_futherinit.argumentsname()).join(","); var _initbody = _currentinit.body() + _futherinit.body(); eval('target.prototype.init=function('+_initargname+'){'+_initbody+'}'); } }; $.object = { extend: function(target, source){ //对象的继承 for(var i in source) target[i] = source[i]; return target; }, clone: function(source){ //对象的复制 return this.extend({}, source) }, hasname: function(obj, name){ //判断是否有这个方法 try{ var is = obj.hasownproperty(name); if(is) return is; return name in obj; }catch(e){ return name in obj; } }, isprototypename: function(obj, name){ //判断是否为原型连方法 return !obj.hasownproperty(name) && name in obj; }, isempty: function(obj){ //判断对象是否空 var i = ""; for(i in obj) break; return !i; }, isdom: function(obj){ return !!obj.nodetype; }, log: function(obj, is){ //打印对象属性 for(var i in obj){ $.log('[ '+i+' : '+obj[i]+' ]', is) } } }; $.array = function(obj){ if(obj.nodetype) return [obj]; return $.try( function(){ return [].slice.call(obj,0); }, function(){ var arr = [], i = 0, temp; while(temp = obj[i++]) arr[arr.length] = temp; return arr; }, function(){ return [].concat(obj); } ) }; $.index = function(obj, objs){ obj = obj.dom ? obj.dom() : obj; //不用while循环的原因是数组中也许存在 0,false, 这种值!!!逆遍历的原因是可以少一个变量 for(var i=objs.length-1; 0<=i; --i){ if(obj === objs[i]) return i; } return -1; }; $.each = function(obj,fn,isdom){ if(!isdom){ //不用while循环的原因是数组中也许存在 0,false, 这种值!!!为什么不逆着遍历 ? 由于array的unique除重,如果逆着来返回的array顺序会有偏差 for(var i = 0, j = obj.length; i < j; ++i) fn.call(obj[i], i, obj); }else{ for(var i in obj) fn.call(obj[i], i, obj); } }; $.log = function(arg, is){ if(!win.console || is){ var div = doc.createelement('div'); div.style.csstext = 'background:#ccc;color:#f00;border-top:1px solid #fff;'; div.innerhtml = 'mes: '+arg; body.appendchild(div); }else{ win.console.log(arg); } }; $.typeof = function(key){ switch(object.prototype.tostring.call(key)){ case '[object array]' : return 'array'; case '[object string]' : return 'string'; case '[object regexp]' : return 'regexp'; case '[object number]' : return 'number'; case '[object function]' : return 'function'; case '[object boolean]' : return 'boolean'; default : switch(key){ case null : return 'null'; case undefined : return 'undefined'; default : return 'object'; } } }; $.try = function(){ for(var i=0,j=arguments.length;i]*>([\s\s]*?)<\/script>/img; $.stringmethod = { strip:function(str){ str = str.replace(/^\s+/, '').replace(/\s+$/, ''); return $.use(str); }, stripscripts:function(str){ return $.use(str.replace(rex_script, '')); }, getscripts:function(str){ str = str.match(rex_script); $.each(str,function(i,o){ o[i] = o[i].replace(rex_script,function(a,b){ return b; }) }); return $.use(str); }, evalscripts:function(str){ eval(""+str); return $.use(str); }, getdom:function(str){ return $.method.tempnode(str); } } /** function */ $.functionmethod = { bind:function(){ var args = $.array(arguments), _fun = args.shift(), _obj = args.shift(); return function(){ return _fun.apply(_obj,args.concat($.array(arguments))); }; }, name:function(fun){ return fun.tostring().match(/function ([\s\s]*?)\(/)[1]; }, argumentsname:function(fun){ return fun.tostring().match(/\(([\s\s]*?)\)/)[1].split(","); }, body:function(fun){ return fun.tostring().match(/\{([\s\s]*)\}/)[1]; } } /*---basicextend---*/ $.use = function(){ switch($.typeof(arguments[0])){ case "array" : return new $._forarray(arguments[0]); case "number" : return new $._fornumber(arguments[0]); case "string" : return new $._forstring(arguments[0]); case "function" : return new $._forfunction(arguments[0]); } } $._forarray = function(arg){ this.value = arg;this.length = arg.length; }; $._fornumber = function(arg){ this.value = arg; }; $._forstring = function(arg){ this.value = arg; }; $._forfunction = function(arg){ this.value = arg; }; $.basicextend = { special:function(oldo,newo){ $.each(newo,function(i,o){oldo[i] = function(){return o[i].apply(null,[this.value].concat(array.prototype.slice.call(arguments)))}},true); }, action:function(){ var basic = $.basicextend; basic.special($._forarray.prototype,$.arraymethod); basic.special($._fornumber.prototype,$.numbermethod); basic.special($._forstring.prototype,$.stringmethod); basic.special($._forfunction.prototype,$.functionmethod); } } $.basicextend.action(); /** /lang */ /*----window----*/ $.window = { outerheight:function(){ return win.innerheight || html.offsetheight; }, outerwidth:function(){ return win.innerwidth || html.offsetwidth; }, innerheight:function(){ return html.clientheight; }, innerwidth:function(){ return html.clientwidth; }, bodyheight:function(){ return body.offsetheight; }, bodywidth:function(){ return html.clientwidth; }, scrollheight:function(){ return html.scrollheight; }, scrollwidth:function(){ return html.scrollwidth; }, scrolltop:function(num){ if(num !== undefined){ html.scrolltop = num; body.scrolltop = num; return; } return html.scrolltop || body.scrolltop; }, scrollleft:function(num){ if(num !== undefined){ html.scrollleft = num; body.scrollleft = num; return; } return html.scrollleft || body.scrollleft; }, onload:function(fun){ if($.typeof(fun) !== "function") return; if(!!win.onload){ var oldfun = win.onload; win.onload = function(){ win.onload = null; oldfun(); fun(); } }else{ win.onload = function(){ win.onload = null; fun(); }; } } } /*----dom----*/ $.dom = { _readyarr:[], ready:function(fun){ if($.typeof(fun) !== "function") return; var _this = this,_arr = _this._readyarr; if(_arr.push(fun) > 1) return; if(!$.browser.ie8){ $(doc).bind("domcontentloaded",function(){ $(doc).unbind("domcontentloaded"); for(var i=0,j=_arr.length;ia','div[title=hello]' 属性选择的时候可以用5种匹配 * @param {dom} node 元素节点 * @param {boolean} is 可以用1,0代替 * @return {array} 返回一个数组 */ var selector = function(str, node, is){ return this instanceof selector ? this.init(str, node, is) : new selector(str, node, is); } selector.prototype = { init:function(str, node, is){ return doc.queryselectorall ? this.query(str, node, is) : this.fixed(str, node, is); }, rex:{ value01:/[^\s>]+/, //获取字符串第一个空格之前的字符; value02:/([#.])?(.+)/, //判断字符串是#,.,字符组成的; value03:/\[(.*[^~*^$])([~*^$]?)=(.+)\]/, //匹配属性用的; 匹配[xxx=xxx] value04:/([\s>])([^\s>]+)/g, //匹配' xxx|>xxx'这种,判断是find还是children value05:/[^[]+/ //获取节点名; }, query:function(str, node, is){ if (!node || node.nodetype === 9){ node = node || doc; return $.array(node.queryselectorall(str)); }else { var tempstr = ''; var tempnode = node; while(tempnode.nodename !== 'body'){ tempstr = tempnode.nodename +' '+tempstr; tempnode = tempnode.parentnode; } return $.array(node.queryselectorall(tempstr +(!is ? ' ' : '>')+ str)); } }, fixed:function(str, node, is){ if (!node) node = doc; var rex = selector.rex; str = (!is ? ' ' : '>')+str; node = [node]; str.replace(rex.value04,function(a,b,c,d){ switch(b){ case ' ': is = false;break; case '>': is = true ;break; } var str = c.match(rex.value02), i = 0, temp, arr = []; while(temp = node[i++]){ switch(str[1]){ case '#': arrnode = selector.selectbyid(str[2], [temp]); break; case '.': arrnode = selector.selectbyclassname(str[2], selector.getnodes('*', temp, is)); break; default : arrnode = selector.selectbyattr(str[2], selector.getnodes(str[2].match(rex.value05)[0], temp, is)); } arr = arr.concat(arrnode); } node = arr; }) return node; }, selectbyid:function(str, nodes){ //通过id查询 var value = (nodes[0].nodetype === 9 ? nodes[0] : nodes[0].ownerdocument).getelementbyid(str); return value ? value : []; }, selectbyclassname:function(str, nodes){ //通过class查询 var temp, arr = [], i = 0, rexclassname = new regexp("\\b"+str+"\\b"); while(temp = nodes[i++]){ if(rexclassname.test(temp.classname)) arr[arr.length] = temp } return arr; }, selectbyattr:function(str, nodes){ //通过属性查找 var rex = selector.rex, str = str.match(rex.value03); if (!str) return $.array(nodes); var attr_name = str[1], //得到节点属性 attr_term = str[2], //得到匹配方法 attr_value = str[3], //得到节点属性值 i = 0, arr = [], temp, rex; switch(attr_term){ case '' : rex = new regexp('^'+attr_value+'$'); break; //匹配开头到结尾 case '~': rex = new regexp('\\b'+attr_value+'\\b'); break; //匹配单词 case '*': rex = new regexp(attr_value); break; //只要有单词出现 case '^': rex = new regexp('^'+attr_value); break; //匹配开头 case '$': rex = new regexp(attr_value+'$'); break; //匹配结尾 } while(temp = nodes[i++]){ var attr = selector.getattr(temp, attr_name); if(rex.test(attr)) arr[arr.length] = temp; } return arr; }, getnodes:function(str, node, is){ if (!is) return node.getelementsbytagname(str); else{ var nodes = node.childnodes, i = 0, temp, rex, arr = []; if (str === '*') rex = /.+/; else rex = new regexp('^'+str+'$','i'); while(temp = nodes[i++]){ if (temp.nodetype === 1 && rex.test(temp.nodename)) arr[arr.length] = temp; } return arr; } }, getattr:function(node, name){ //为了得到class的兼容方法 var value = node.getattribute(name); if (value) return value; value = node.getattributenode(name); return value ? value.nodevalue : null; } }; 'query fixed rex selectbyid selectbyclassname selectbyattr getattr getnodes'.replace(/\w+/g,function(n){ //绑定静态方法 selector[n] = selector.prototype[n]; }); $.selector = selector; //全局引用 /* /somesayss选择器 v1.1.0 */ /** * @fileoverview somesayss事件系统 v1.1.0 2013.4.18 * 依赖 data类 selector类 * @param {dom} node 对象节点 * @param {string} en * @param {function} fn */ var event = function(node, en, fn){ return this instanceof event ? this.init(node, en, fn) : new event(node, en, fn); } event.prototype = { init: function(node, en, fn){ this.bind(node, en, fn); }, _add: function(node, en, fn){ node.addeventlistener ? node.addeventlistener(en, fn, false) : node.attachevent("on" + en, fn); }, _remove: function(node, en, fn){ node.removeeventlistener ? node.removeeventlistener(en, fn, false) : node.detachevent("on" + en, fn); }, istousehandleevent: function(node, en){ var hasname = $.object.hasname; //判断条件是当节点有这个事件的时候就去普通绑定;如果没有的话再去找代理事件,如果找到就去代理绑定; return !hasname(node, 'on'+en) && hasname(this.handleevent, en); }, iscopycutpaste: function(en){ return (en === 'copy' || en === 'cut' || en === 'paste') && $.browser.ie8 }, bind: function(node, en, fn){ var self = this, data = data, eventdata = data.catche.system.event, id = data.set(node); //分配id空间 eventdata[id] || (eventdata[id] = {}); //分配事件空间 eventdata[id][en] || (eventdata[id][en] = {}); //初始化arrfn eventdata[id][en]['arrfn'] || (eventdata[id][en]['arrfn'] = []); //开始堆fn,并且当计数大于1的时候直接返回 if(eventdata[id][en]['arrfn'].push(fn) > 1) return this; //初始化代理函数 var handle = function(e){ var e = eventobject(e, node, en), returnvalue = []; $.each(eventdata[id][en]['arrfn'], function(){ returnvalue[returnvalue.length] = this.call(node, e); }); //让return false 正确执行e.preventdefault(); if($.index(false, returnvalue) !== -1) e.preventdefault(); } //如果节点无这个事件就去代理事件那边或者是ie678中的copy,cut,paste事件 if(self.istousehandleevent(node, en) || self.iscopycutpaste(en)){ eventfixed(node, en, handle); return this; } eventdata[id][en]['handle'] = handle; //注册代理函数 self._add(node, en, handle); return this; }, unbind: function(node, en, fn){ var self = this, data = data, id = data.get(node), eventdata; //代码防御:如果id不存,或者eventdata不存在就返回 if(!id || !(eventdata = data.catche.system.event[id])) return this; //代码防御:如果en存在的话判断eventdata[en]是否存在 if(en && !eventdata[en]) return this; //事件反注册以及数据的清理 var enevtremove = function(node, eventdata, en){ //反绑定ie678中的copy,cut,paste事件 if(self.iscopycutpaste(en) && node.nodetype === 9){ self.unbinddelegates('html', node, en); } //如果不存在则删除代理事件,事件反注册 if(self.istousehandleevent(node, en)){ self._remove(node, self.handleevent[en], eventdata[en]['handle']); //如果en为focusin或者focusout并且node不是input,select,textarea; if((en === 'focusin' || en === 'focusin') && !/input|select|textarea/.test(node.nodename)){ self.unbinddelegates('input select textarea', node, en); } }else{ self._remove(node, en, eventdata[en]['handle']); } //把en对应的对象销毁 delete eventdata[en]; } //当存在node, en的情况 if(arguments.length === 2){ enevtremove(node, eventdata, en); } //当只存在node的情况 else if(arguments.length === 1){ for(var i in eventdata){ enevtremove(node, eventdata, i); } } //当存在node, en, fn的情况 else if(arguments.length === 3){ var arr = eventdata[en]['arrfn']; //在arr中排出fn; self._except(arr, fn); //如果arr中已经无数据的,清除数据! if(arr.length === 0) enevtremove(node, eventdata, en); } //如果此eventdata 为空了,删除此节点的数据 if($.object.isempty(eventdata)) delete data.catche.system.event[id]; return this; }, unbinddelegates: function(str, node, en){ //对于focusin,focusout特别处理函数 var self = this; var neednodes = []; str.replace(/\w+/g, function(a){ neednodes = neednodes.concat(selector(a, node)); }); if(neednodes.length){ $.each(neednodes, function(){ var id = data.get(this), eventdata = data.catche.system.event[id]; //如果eventdata中的arrfn有值就不去unbind if(eventdata[en]['arrfn']) return; //反绑定事件,删除内存; self._remove(this, self.handleevent[en], eventdata[en]['handle']); delete eventdata[en]; //如果此eventdata 为空了,删除此节点的数据 if($.object.isempty(eventdata)) delete data.catche.system.event[id]; }) } return this; }, _except: function(arr,arg){ var i = $.index(arg,arr); if(i === -1) return arr; arr.splice(i,1); return arr; }, handleevent: { 'focusin': 'focus', 'focusout': 'blur', 'mouseenter': 'mouseover', 'mouseleave': 'mouseout', 'mousewheel': 'dommousescroll' } } '_add _remove _addup _removeup bind unbind _except handleevent istousehandleevent iscopycutpaste unbinddelegates'.replace(/\w+/g,function(n){ event[n] = event.prototype[n] }) /** * @fileoverview somesayss事件对象 v1.1.0 2013.4.19 * 对事件系统的支持 * @param {object} e 事件对象 */ var eventobject = function(e, node, en){ return this instanceof eventobject ? this.init(e, node, en) : new eventobject(e, node, en); } eventobject.prototype = { init: function(e, node, en){ this.e = e || window.event; this.node = node; this.type = en; //监听源 this.currenttarget = e.currenttarget || node; //监听目标 this.target = e.target || e.srcelement; //页面的鼠标位置 this.pointerx = e.pagex || (e.clientx +(html.scrollleft || body.scrollleft)); this.pointery = e.pagey || (e.clienty +(html.scrolltop || body.scrolltop)); this.relatedtarget = e.relatedtarget || (e.fromelement === this.target ? e.toelement : e.fromelement); this.wheeldelta = (e.wheeldelta || -e.detail) < 0 ? true : false; }, stoppropagation: function(){ var e = this.e, eventdata = data.catche.system.event, id = data.set(this.node);; e.stoppropagation ? e.stoppropagation() : e.cancelbubble = true; //代码防御 if(!id) return this; eventdata[id][this.type]['stoppropagation'] = 1; }, preventdefault: function(){ var e = this.e; e.preventdefault ? e.preventdefault() : e.returnvalue = false; }, stop: function(){ this.stoppropagation(); this.preventdefault(); } } /** * @fileoverview somesayss事件的补丁 v1.1.0 2013.4.19 * 做事件的兼容处理 * @param {object} e 事件对象 */ var eventfixed = function(node, en, handle){ return this instanceof eventfixed ? this.init(node, en, handle) : new eventfixed(node, en, handle); } eventfixed.prototype = { init: function(node, en, handle){ this.bind(node, en, handle); }, bind: function(node, en, handle){ var self = this, handleevent = event.handleevent[en] || en, eventdata = data.catche.system.event, id = data.get(node), newhandle; switch(en){ case 'focusin': case 'focusout': newhandle = function(e){ self.propagation(node, en, e, eventdata); }; //如果node不是input,select,textarea,则在此节点的内部的所有表单域监听 if(!/input|select|textarea/.test(node.nodename)){ self.eventdelegates('input select textarea', node, en, eventdata); } break; case 'mouseenter': case 'mouseleave': newhandle = function(e){ self.mouseenterleave(node, en, e, eventdata); }; break; case 'mousewheel': newhandle = handle; break; case 'copy': case 'cut': case 'paste': newhandle = handle; if(node.nodetype === 9){ self.eventdelegates('html', node, en, eventdata); } break } //代码防御:保证事件只绑定一次! if(!eventdata[id][en]['handle']){ //绑定代理事件 eventdata[id][en]['handle'] = newhandle; event._add(node, handleevent, newhandle); } return this; }, propagation: function(node, en, e, eventdata){ var self = this, id, stop; do{ id = data.get(node); //如果id不存在就直接去下一次循环 if(!id || !eventdata[id]) continue; //如果stop存在直接跳出 if(stop) break; //在这里创建事件对象;node改变啦 var e = eventobject(e, node, en); var arrfn = eventdata[id][en]['arrfn']; if(!arrfn) continue; $.each(arrfn, function(){ this.call(node, e); }); stop = eventdata[id][en]['stoppropagation']; }while(node = node.parentnode); return this; }, mouseenterleave: function(node, en, e, eventdata){ var id = data.get(node), e = eventobject(e, node, en), rel = e.relatedtarget; e.stoppropagation(); if($.dom.contains(node,rel)) return this; $.each(eventdata[id][en]['arrfn'],function(){ this.call(node,e); }) return this; }, eventdelegates: function(str, node, en, eventdata){ var neednodes = [], self = this, handleevent = event.handleevent[en] || en; str.replace(/\w+/g, function(a){ neednodes = neednodes.concat(selector(a, node)); }); if(neednodes.length){ $.each(neednodes, function(){ var tempnode = this, tempid = data.set(tempnode); eventdata[tempid] || (eventdata[tempid] = {}); eventdata[tempid][en] || (eventdata[tempid][en] = {}); //代码防御:保证事件只绑定一次! var oldhandle = eventdata[tempid][en]['handle']; if(oldhandle){ event._remove(tempnode, handleevent, oldhandle); } var newhandle = function(e){ self.propagation(tempnode, en, e, eventdata); }; //绑定代理事件 eventdata[tempid][en]['handle'] = newhandle; event._add(tempnode, handleevent, newhandle); }) } return this; } } $.event = event; /** /somesayss事件系统 */ /*----event----*/ $.bindevent = { add:function(node,en,fu){ node.addeventlistener ? node.addeventlistener(en,fu,false) : node.attachevent("on" + en, fu); }, remove:function(node,en,fu){ node.removeeventlistener ? node.removeeventlistener(en,fu,false) : node.detachevent("on" + en, fu); }, _eventtype:'mouseenter,mouseleave,mousewheel', bind:function(node,en,fu){ var _this = this , _data = $.data , _getdata = _data.get , _setdata = _data.set; if(!_getdata(node,"event")) _setdata(node,"event",{}); if(!_getdata(node,"event")[en]) _getdata(node,"event")[en] = []; if(_getdata(node,"event")[en].push(fu) > 1) return; if(this._eventtype.indexof(en) > -1 && !$.object.hasname(node,"on"+en)) return $.eventfix[en](node); var agent = function(e){ var e = new $.event(e || win.event); $.each(_getdata(node,"event")[en],function(){ this.call(node,e); }) }; _setdata(node,"agent"+en,agent); _this.add(node,en,agent); }, unbind:function(node,en){ var _agent = $.data.get(node,"agent"+en); var _object = $.object; if(!_object.hasname(node,"on"+en)){ switch(en){ case "mouseenter" : this.remove(node,"mouseover",_agent); break; case "mouseleave" : this.remove(node,"mouseout",_agent); break; case "mousewheel" : this.remove(node,"dommousescroll",_agent); break; } }else{ this.remove(node,en,_agent); } $.data.clear(node,"agent"+en); delete $.data.get(node,"event")[en]; if(_object.isempty($.data.get(node,"event"))) $.data.clear(node,"event"); } } $.event = function(e){ var _this = this , d = doc; _this.e = e; _this.target = e.target || e.srcelement; _this.pointerx = e.pagex || (e.clientx +(html.scrollleft || body.scrollleft)); _this.pointery = e.pagey || (e.clienty +(html.scrolltop || body.scrolltop)); _this.relatedtarget = e.relatedtarget || (e.fromelement === _this.target ? e.toelement : e.fromelement); _this.wheeldelta = (e.wheeldelta || -e.detail) < 0 ? true : false; } $.event.prototype = { stoppropagation:function(){ var e = this.e; e.stoppropagation ? e.stoppropagation() : e.cancelbubble = true; }, preventdefault:function(){ var e = this.e; e.preventdefault ? e.preventdefault() : e.returnvalue = false; }, stop:function(){ var e = this.e; if(e.preventdefault){e.preventdefault();e.stoppropagation();}else{e.returnvalue = false;e.cancelbubble = true;} } } $.eventfix = { mouseenter:function(node){ var agent = function(e){ var e = new $.event(e || win.event); var rel = e.relatedtarget; e.stoppropagation(); if($.dom.contains(node,rel)) return; $.each($.data.get(node,"event")["mouseenter"],function(){ this.call(node,e); }) } $.data.set(node,"agentmouseenter",agent); $.bindevent.add(node,"mouseover",agent); }, mouseleave:function(node){ var agent = function(e){ var e = new $.event(e || win.event); var rel = e.relatedtarget; e.stoppropagation(); if($.dom.contains(node,rel)) return; $.each($.data.get(node,"event")["mouseleave"],function(){ this.call(node,e); }) } $.data.set(node,"agentmouseleave",agent); $.bindevent.add(node,"mouseout",agent); }, mousewheel:function(node){ var agent = function(e){ var e = new $.event(e || win.event); e.stoppropagation(); $.each($.data.get(node,"event")["mousewheel"],function(){ this.call(node,e); }) } $.data.set(node,"agentmousewheel",agent); $.bindevent.add(node,"dommousescroll",agent); } } /** * @fileoverview somesayss dom方法 v1.1.0 * @param {array} eles 这里的eles传入的都是一个数组; */ $.method = { /** * dom操作之遍历 */ find:function(eles,str){ //modify 2013,4,9 var newarr = []; $.each(eles,function(){ var _temp = selector(str,this); newarr = newarr.concat(_temp); }) return $(newarr); }, children:function(eles,str){ //modify 2013,4,9 var newarr = []; $.each(eles,function(){ var _temp = selector(str,this,1); newarr = newarr.concat(_temp); }) return $(newarr); }, unique: function(eles){ //modify 2013,4,9 去掉重复的元素 var val = [], hash = {}; $.each(eles,function(){ var id = data.set(this); if(!hash[id]){ hash[id] = 1; val[val.length] = this; } }); return val; }, select: function(eles, str){ //modify 2013,4,9 对一个元素的数组进行筛选 @依赖 *selector* var sel = selector, str = str.match(sel.rex.value02); switch(str[1]){ case '#': return sel.selectbyid(str[2], eles); case '.': return sel.selectbyclassname(str[2], eles); default : return sel.selectbyattr(str[2], eles); } }, _findnode: function(eles, first, type){ //modify 2013,4,9 var arr = [], node; $.each(eles, function(){ node = this[first]; do{ if(node.nodetype === 1){ arr[arr.length] = node; break; } } while(node = node[type]); }); return arr; }, _findnodes:function(eles,type){ //modify 2013,4,9 var arr = [], node; $.each(eles, function(){ node = thisnode = this; type.replace(/\w+/g, function(a){ while(node = node[a]){ if(node.nodetype === 1) arr[arr.length] = node; } node = thisnode; }) }); arr = $.method.unique(arr); return arr; }, prev: function(eles){ //modify 2013,4,9 return $($.method._findnode(eles, 'previoussibling', 'previoussibling')); }, next: function(eles){ //modify 2013,4,9 return $($.method._findnode(eles, 'nextsibling', 'nextsibling')); }, first: function(eles){ //modify 2013,4,9 return $($.method._findnode(eles, 'firstchild', 'nextsibling')); }, last: function(eles){ //modify 2013,4,9 return $($.method._findnode(eles, 'lastchild', 'previoussibling')); }, parent: function(eles){ //modify 2013,4,9 return $($.method._findnode(eles, 'parentnode')); }, prevall: function(eles, str){ //modify 2013,4,9 var arr = $.method._findnodes(eles, "previoussibling"); return str ? $($.method.select(arr, str)) : $(arr); }, nextall: function(eles, str){ //modify 2013,4,9 var arr = $.method._findnodes(eles, "nextsibling"); return str ? $($.method.select(arr, str)) : $(arr); }, siblings: function(eles, str){ //modify 2013,4,9 var arr = $.method._findnodes(eles, "previoussibling nextsibling"); return str ? $($.method.select(arr, str)) : $(arr); }, dom: function(eles,num){ //modify 2013,4,9 return !num ? eles[0] : eles[num]; }, eq: function(eles,num){ //modify 2013,4,9 return $(eles[num ? num : 0]); }, each: function(eles,fn){ //modify 2013,4,9 var i = 0, temp; while(temp = eles[i++]) fn.call(temp, i-1, eles); return $(eles); }, index: function(eles,node){ //modify 2013,4,9 return $.index(node,eles); }, filter: function(eles,fun){ //modify 2013,4,9 var arr = []; $.each(eles, function(i, o){ if(fun.call(this, i, o)) arr[arr.length] = this; }) return $(arr); }, slice: function(){ var arr = $.array(arguments),eles = arr.shift(); return $([].slice.apply(eles,arr)); }, /** /dom操作之遍历 */ /** * dom操作之文档操作 */ cleardata: function(node, is){ //保证此节点和它的子节的数据clear掉 if(is) data.clear(node); $(node).find('*').each(function(){ data.clear(this); }); }, remove: function(eles){ //modify 2013,4,11 $.each(eles,function(){ $.method.cleardata(this, 1); this.parentnode.removechild(this); }); return $(eles); }, empty: function(ele){ //modify 2013,4,11 return $(ele).html(''); }, tempnode: function(arg){ var node = doc.createdocumentfragment(); if($.typeof(arg) === "string"){ var div = doc.createelement("div"); div.innerhtml = arg; while(div.firstchild){ node.appendchild(div.firstchild); } }else if($.typeof(arg) === "object"){ var arr = $.array(arg), i = 0, temp; while(temp = arr[i++]) node.appendchild(temp); } return node; }, append: function(eles, arg){ var temp = $.method.tempnode(arg); $.each(eles, function(){ this.appendchild(temp.clonenode(true)); }); return $(eles); }, prepend:function(eles){ if($.typeof(arguments[1]) === "string"){ arguments[1] = $.method.tempnode(arguments[1]); }else{ try{ arguments[1] = arguments[1].dom(); }catch(e){} } eles[0].insertbefore(arguments[1],eles[0].firstchild); return $(eles); }, after:function(eles){ if($.typeof(arguments[1]) === "string"){ arguments[1] = $.method.tempnode(arguments[1]); }else{ try{ arguments[1] = arguments[1].dom(); }catch(e){} } eles[0].parentnode.insertbefore(arguments[1],eles[0].nextsibling); return $(eles); }, before:function(eles){ if($.typeof(arguments[1]) === "string"){ arguments[1] = $.method.tempnode(arguments[1]); }else{ try{ arguments[1] = arguments[1].dom(); }catch(e){} } eles[0].parentnode.insertbefore(arguments[1],eles[0]); return $(eles); }, replace:function(eles){ if($.typeof(arguments[1]) === "string"){ arguments[1] = $.method.tempnode(arguments[1]); }else{ try{ arguments[1] = arguments[1].dom(); }catch(e){} } //cleardata -> ele eles[0].parentnode.replacechild(arguments[1],eles[0]); return $(eles[0]); }, clone:function(eles, is){ //cleardata -> ele return eles[0].clonenode(!is); }, text:function(eles,str){ var innertext = ("textcontent" in eles[0]) ? "textcontent" : "innertext"; if($.typeof(str) !== 'string') return $.use(eles[0][innertext]).value; //cleardata -> all eles[0][innertext] = str; return $(eles); }, html:function(eles,str){ //modify 2013,4,11 if((!str && str !== '') || $.typeof(str) === 'object') return eles[0].innerhtml; $.each(eles, function(){ $.method.cleardata(this); this.innerhtml = ""+str; }); return $(eles); }, /** /dom操作之文档操作 */ /** * data的快捷操作 */ data: function(eles, name, value){ if(value){ $.each(eles, function(){ data.set(this, name, value); }); return $(eles); } var type, arr = []; switch(arguments.length){ case 1: type = 'set'; break; case 2: type = 'get'; break; case 3: type = 'set'; break; } if(eles.length === 1) return data[type](eles[0], name, value); $.each(eles, function(){ arr[arr.length] = data[type](this, name, value); }) return arr; }, removedata: function(eles, nane){ $.each(eles, function(){ data.remove(this, nane); }) return $(eles); }, cleardata: function(eles){ $.each(eles, function(){ data.clear(this); }) return $(eles); }, /** /data的快捷操作 */ bind:function(eles,en,fu){ $.each(eles,function(){ $.bindevent.bind(this,en,fu); }); return $(eles); }, unbind:function(eles,en){ $.each(eles,function(){ $.bindevent.unbind(this,en); }); return $(eles); }, animate:function(eles,obj){ $.each(eles,function(){ obj.node = this; new $.animate(obj); }); return $(eles); }, animatestop:function(eles){ $.each(eles,function(){ var val = $.data.get(this,"animate"); if(!!val) val.stop(); }); return $(eles); }, animatetoend:function(eles){ $.each(eles,function(){ var val = $.data.get(this,"animate"); if(!!val) val.toend(); }); return $(eles); }, show:function(eles,str){ switch(str){ case undefined: case 0: $.each(eles,function(){ this.style.display = "block"; }); break; case 1: $.each(eles,function(){ this.style.display = "inline"; }); break; default: $.each(eles,function(){ this.style.display = str; }); } return $(eles); }, hide:function(eles){ $.each(eles,function(){ this.style.display = "none"; }); return $(eles); }, visible:function(eles) { return !!eles[0].offsetwidth || $(eles[0]).css("display") !== "none"; }, toggle:function(eles,type){ $.each(eles,function(){ $.method[$.method.visible([this]) ? "hide" : "show"]([this],type); }) return $(eles); }, hasclass:function(eles,str){ if(!str) return false; return new regexp("\\b"+str+"\\b").test(eles[0].classname); }, addclass:function(eles,str){ $.each(eles,function(){ if($.method.hasclass([this],str)) return; this.classname = this.classname + " " +str; }); return $(eles); }, removeclass:function(eles,str){ if(!str){ $.each(eles,function(){this.classname = ""}); return $(eles); }else{ $.each(eles,function(){ if(!$.method.hasclass([this],str)) return; this.classname = $.use(this.classname.replace(str,"").replace(/\s+/g," ")).strip().value; }); return $(eles); } }, toggleclass:function(eles,str){ var _met = $.method; $.each(eles,function(){_met.hasclass([this],str) ? _met.removeclass([this],str) : _met.addclass([this],str)}); return $(eles); }, css:function(eles,a,b){ var _val $.each(eles,function(){ _val = new $.style(this,a,b).fire(); }); return (_val === true) ? $(eles) : _val ; }, attr:function(eles,name,value){ if(!value){ var _val = eles[0].getattributenode(name); return _val ? _val.nodevalue : null; }else{ var _att = doc.createattribute(name); _att.nodevalue = value; $.each(eles,function(){ var clone = _att.clonenode(true); if(!clone.nodevalue) clone.nodevalue = value; this.setattributenode(clone) }); return $(eles); } }, removeattr:function(eles,name){ if(!name) return $(eles); switch(name){ case "class": case "classname": eles[0].removeattribute("class"); eles[0].removeattribute("classname"); break; default: $.each(eles,function(){this.removeattribute(name)}) break; } return $(eles); }, position:function(eles){ return { top:eles[0].offsettop, left:eles[0].offsetleft }; }, offset:function(eles){ //getboundingclientrect var _offset = { top:0, left:0 }; while(eles[0].offsetparent != null){ _offset.top += eles[0].offsettop; _offset.left += eles[0].offsetleft; eles[0] = eles[0].offsetparent; } return _offset; }, width:function(eles){ eles[0].style.zoom = 1; return eles[0].clientwidth - ($(eles).css("paddingright") + $(eles).css("paddingleft")); }, innerwidth:function(eles){ eles[0].style.zoom = 1; return eles[0].clientwidth; }, outerwidth:function(eles){ eles[0].style.zoom = 1; return eles[0].offsetwidth; }, height:function(eles){ eles[0].style.zoom = 1; return eles[0].clientheight - ($(eles).css("paddingright") + $(eles).css("paddingleft")); }, innerheight:function(eles){ eles[0].style.zoom = 1; return eles[0].clientheight; }, outerheight:function(eles){ eles[0].style.zoom = 1; return eles[0].offsetheight; } } /** /somesayss dom方法 v1.1.0 */ /** * @fileoverview somesayss som对象工厂 v1.1.0 * @param {array} eles 这里的eles传入的都是一个数组; */ var somobject = function(elems){ return this instanceof somobject ? this.init(elems) : new somobject(elems); } somobject.prototype = { init: function(elems){ if(!this.isarray(elems)) elems = $.array(elems); this.setarray(elems); }, setarray: function(elems){ this.length = 0; //为了让ie67,拥有length属性 [].push.apply(this,elems); }, isarray: function(obj){ //判断是否为array的简略方法,$.typeof的专属版 return object.prototype.tostring.call(obj) === '[object array]'; }, valueof: function(){ return [].slice.call(this); }, splice :[].splice, //为了在firfox下看的更像数组 shift :[].shift, unshift :[].unshift, pop :[].pop, push :[].push, sort :[].sort, concat :[].concat, slice :[].slice }; $.each($.method,function(i,o){ somobject.prototype[i] = function(){ return o[i].apply(null,[[].slice.call(this)].concat([].slice.call(arguments))); } },true); /** /somesayss som对象工厂 v1.1.0 */ /*----style,base----*/ $.style = $.class.creat(); $.style.prototype = { init:function(node,pro,con){ this.node = node; this.pro = pro; this.con = con; }, _cacherex:{ float: $.browser.ie8 ? "stylefloat" : "cssfloat", rex1: /\-(\w)/g, rex2: /px$/, rex3: /\d+/, rex4: /^rgb/, rex5: /\d+/g, rex6: /^#/, rex7: /\w/g }, fire:function(){ var _this = this; if($.typeof(_this.pro) === "object") return _this.setstyle(_this.pro); var con = _this.con, iscon = !!con, pro = !iscon ? _this.formatstring(_this.pro) : _this.pro, node = _this.node; newobj = {}; switch(pro){ case "top" : if(!iscon) return $.method.position([node]).top; break; case "left" : if(!iscon) return $.method.position([node]).left; break; case "float" : newobj[_this._cacherex.float] = ""; return !iscon ? _this.getstyle(newobj) : _this.setstyle({float:con}); break; case "opacity" : newobj[pro] = con; return _this.foropacity(newobj); break; case "width" : if(!iscon){ var _valwidth = _this.getstyle({width:''}); return (_valwidth === "auto") ? $.method.width([node]) : _valwidth; } break; case "height" : if(!iscon){ var _valheight = _this.getstyle({height:''}); return (_valheight === "auto") ? $.method.height([node]) : _valheight; } break; } newobj[pro] = con; return !iscon ? _this.getstyle(newobj) : _this.setstyle(newobj); }, formatstring:function(str){ var _cacherex = this._cacherex; return str.replace(_cacherex.rex1, function(a, b){ return b.touppercase(); }) }, formatnumber:function(num){ var _cacherex = this._cacherex; if(_cacherex.rex2.test(num)) { return parseint(num); }else if(_cacherex.rex4.test(num)){ var _colornum = num.match(_cacherex.rex5); var _temps = '' _colornum.each(function(i,o){ _temps += (+o[i]).formatcolor(); }); return "#"+_temps; }else if(_cacherex.rex6.test(num) && num.length === 4){ return num.replace(_cacherex.rex7,function(a,b){ return a+a; }) }else{ return num; } }, foropacity:function(newobj){ var _this = this, _node = _this.node, _num = newobj.opacity; if(!!_num){ _node.style.opacity = _num; _node.style.filter = "alpha(opacity="+(_num*100)+")"; }else{ var _value = _this.getstyle.call(_this,newobj); return !!_value ? +_value : 1; } }, getstyle:function(newobj){ var _this = this,node = _this.node,showstyle = null; win.getcomputedstyle ? showstyle = win.getcomputedstyle(node, null) : showstyle = node.currentstyle; for(var i in newobj) if(showstyle[i]) return _this.formatnumber(showstyle[i]); }, setstyle:function(newobj){ var _this = this, _oldval = _this.node.style.csstext, temps= !_oldval ? "" : (_oldval+";"); for(var i in newobj) temps += i+":"+newobj[i]+";"; if($.object.hasname(newobj,"opacity")) temps += "filter:alpha(opacity="+(newobj["opacity"]*100)+")"; _this.node.style.csstext = temps; return true; } } /*----animate----*/ $.animate = $.class.creat(); $.animate.prototype = { init:function(opat){ this.opat = { node:null, time:500, ease:"easeinoutexpo", callback:function(){} }; $.object.extend(this.opat,opat||{}); this.action(); }, ease:{ easeinback: function(pos) { var s = 1.70158; return (pos) * pos * ((s + 1) * pos - s); }, easeoutback: function(pos) { var s = 1.70158; return (pos = pos - 1) * pos * ((s + 1) * pos + s) + 1; }, easeinoutback: function(pos) { var s = 1.70158; if ((pos /= 0.5) < 1) return 0.5 * (pos * pos * (((s *= (1.525)) + 1) * pos - s)); return 0.5 * ((pos -= 2) * pos * (((s *= (1.525)) + 1) * pos + s) + 2); }, bounce: function(pos) { if (pos < (1 / 2.75)) { return (7.5625 * pos * pos); } else if (pos < (2 / 2.75)) { return (7.5625 * (pos -= (1.5 / 2.75)) * pos + .75); } else if (pos < (2.5 / 2.75)) { return (7.5625 * (pos -= (2.25 / 2.75)) * pos + .9375); } else { return (7.5625 * (pos -= (2.625 / 2.75)) * pos + .984375); } }, bouncepast: function(pos) { if (pos < (1 / 2.75)) { return (7.5625 * pos * pos); } else if (pos < (2 / 2.75)) { return 2 - (7.5625 * (pos -= (1.5 / 2.75)) * pos + .75); } else if (pos < (2.5 / 2.75)) { return 2 - (7.5625 * (pos -= (2.25 / 2.75)) * pos + .9375); } else { return 2 - (7.5625 * (pos -= (2.625 / 2.75)) * pos + .984375); } }, linear: function(pos) { return pos }, spring: function(pos) { return 1 - (math.cos(pos * 4.5 * math.pi) * math.exp( - pos * 6)); }, easeinexpo: function(pos){ return (pos==0) ? 0 : math.pow(2, 10 * (pos - 1)); }, easeoutexpo: function(pos){ return (pos==1) ? 1 : -math.pow(2, -10 * pos) + 1; }, easeinoutexpo: function(pos){ if(pos==0) return 0; if(pos==1) return 1; if((pos/=0.5) < 1) return 0.5 * math.pow(2,10 * (pos-1)); return 0.5 * (-math.pow(2, -10 * --pos) + 2); }, wobble: function(pos) { return (-math.cos(pos*math.pi*(9*pos))/2) + 0.5; }}, requestanimationframe:function(){ return win.requestanimationframe || win.mozrequestanimationframe || win.webkitrequestanimationframe || win.msrequestanimationframe || win.orequestanimationframe || function(callback) { settimeout(callback, 1000 / 60); } }, formatstring:function(str){ if($.typeof(str) === "number") return str; return +str.match(this._cache._rex1)[0] }, _cache:{ _rex1 : /[+|-]?\d+(\.\d+)?/, _arr1 : ["left","top","width","height","padding-left","padding-right","font-size","line-height","padding-top","padding-bottom","opacity","margin-left","margin-right","margin-top","margin-bottom"] }, action:function(){ var _this = this, _opat = _this.opat, _animate = _this.requestanimationframe(), _timestar = new date().gettime(), _ease = _this.ease[_opat.ease], _node = $(_opat.node), _array = _this._cache._arr1, _begin = {}, _end = {}, _change = {}, _hasopacity = $.object.hasname(_opat,"opacity"), _isrunit = false; $.each(_opat,function(i,o){ if($.use(_array).inarray(i)){ _isrunit = true; _begin[i] = _node.css(i); _end[i] = _this.formatstring(o[i]); _change[i] = _end[i] - _begin[i]; _end[i] = _end[i]+"px"; } },true); if(!_isrunit) return; if(_hasopacity){ _begin["opacity"] = _begin["opacity"]*100; _change["opacity"] = _change["opacity"]*100; _end["opacity"] = _this.formatstring(_end["opacity"]); } _animate(function(){ var _timechange_ = new date().gettime() - _timestar, _this_ = _this, _opat_ = _opat, _node_ = _node, _changepos_ = _ease(_timechange_ / _opat_.time), _nextpos = (function(){ var newo = {}; for(var i in _begin){ newo[i] = _begin[i] + math.ceil(_changepos_*_change[i])+"px"; } return newo; })(); $.data.set(_node_.dom(),"animate",_this_); if(_hasopacity) _nextpos["opacity"] = _this_.formatstring(_nextpos["opacity"])/100; if(_this_.animatestop){ _opat_.callback(); $.data.clear(_node_.dom(),"animate"); return; } if(_this_.animatetoend){ _node_.css(_end); _opat_.callback(); $.data.clear(_node_.dom(),"animate"); return; } if(_timechange_ >= _opat_.time){ _node_.css(_end); _opat_.callback(); $.data.clear(_node_.dom(),"animate"); return; } _node_.css(_nextpos); _animate(arguments.callee); }) }, animatestop:false, stop:function(){ this.animatestop = true; }, animatetoend:false, toend:function(){ this.animatetoend = true; } } /*---img---*/ $.imageload = $.class.creat(); $.imageload.prototype = { init:function(){ this.opat = { url:null, node:null, callback:function(){} }; $.object.extend(this.opat,arguments[0]||{}); var _url = this.opat.url; var _node = this.opat.node; if(!_url) return; switch($.typeof(_url)){ case "array" : return _url.length !== 0 ? this.fire() : undefined; case "string" : if(!_node){ return this.base(_url,this.opat.callback); } else{ if(!_node.img) _node.img = new image(); return this.only(); } } }, fire:function(){ var _this = this,_opat = _this.opat,guid=0; $.each(_opat.url,function(i,o){ _this.base(o[i],function(url){ guid++; if(guid < _opat.url.length) return; _opat.callback(_opat.url); }) }) }, only:function(){ var _this = this,_opat = _this.opat; var _url = _opat.url; var _node = _opat.node; var _img = _node.img; _img.onload = null; _img.src = _url; if(_img.complete == false){ _img.onload = function(){ _img.onload = null; _opat.callback(_url); _node.img = null; }; }else{ _opat.callback(_url); _node.img = null; } }, base:function(url,callback){ var _opat = this.opat,_img = new image(); _img.src = url; if(_img.complete == false){ _img.onload = function(){ _img.onload = null; callback(url); }; }else{ callback(url); } } } /*----script----*/ $.scriptload = $.class.creat(); $.scriptload.prototype = { init:function(){ this.opat = { url:null, isasyn:true, success:function(){}, error:function(){} }; $.object.extend(this.opat,arguments[0]||{}); if(!this.opat.url) return; this.fire(); }, fire:function(){ var _this = this, _opat = _this.opat; var _url = _opat.url; switch($.typeof(_url)){ case "array" : return _opat.isasyn ? _this.asynload() : _this.synload(); case "string" : return _this.bind_base(_url,_opat.success,_opat.error); } }, synload:function(){ var _this = this, _opat = _this.opat; var _length = _opat.url.length; var _guid = 0; var _main = function(){ _this.bind_base(_opat.url[_guid],function(){ ++_guid; if(_guid < _length) return _main(); _opat.success(); },function(){ _opat.error(_opat.url[_guid]); }) } _main(); }, asynload:function(){ var _this = this, _opat = _this.opat; var _length = _opat.url.length; var _guid = 0; $.each(_opat.url,function(i,o){ _this.bind_base(o[i],function(){ ++_guid; if(_guid < _length) return; _opat.success(); },function(){ _opat.error(o[i]); }); }); }, bind_base:function(url,callback,error){ var script = doc.createelement('script'); var isdown = false; script.src = url; script.type = 'text/javascript'; body.appendchild(script); script.onload = function(){ script.onerror = script.onload = script.onreadystatechange = null; if(isdown) return; isdown = true; callback(); } script.onerror = function(){ script.onerror = script.onload = script.onreadystatechange = null; if(isdown) return; isdown = true; error(url); } script.onreadystatechange = function(){ if(script.readystate === "loaded" || script.readystate === "complete"){ script.onerror = script.onload = script.onreadystatechange = null; if(isdown) return; isdown = true; try{ callback(); }catch(e){ error(url); } } } } } /*----jsonp----*/ $.jsonp = $.class.creat(); $.jsonp.prototype = { init:function(){ this.opat = { url:null, data:null, jsonp:"jsonpcallback", success:function(){}, error:function(){} }; $.object.extend(this.opat,arguments[0]||{}); if(!this.opat.url) return; this.fire(); }, fire:function(){ var _this = this, _opat = _this.opat; var _url = _opat.url+"?"+_opat.data+"&callback="+_opat.jsonp; var _iserror = false; win[_opat.jsonp] = function(data){ _opat.success(data); _iserror = true; win[_opat.jsonp] = undefined; $.try(function(){ delete win[_opat.jsonp] }); } new $.scriptload({ url:_url, success:function(){ if(_iserror) return; _opat.error(); }, error:_opat.error }) } } /*----ui---*/ $.ui = {} /*全局引用*/ win["somesayss"] = $; }(window, document);