一个类似于jq的小型库

Posted qq281113270

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了一个类似于jq的小型库相关的知识,希望对你有一定的参考价值。

本人写了一个类似于jq的小型库,不过只是写了部分方法而已。并没有jq那么全面,下面就介绍下有哪些方法可以使用

第一个是选择器,

选择器比较简单 只支持ID选择器 $(‘#id_name’)

                     Class选择器$(‘.class_name’)

                     标签选择器$(‘tag _name’)

并没有像jq那样拥有高级的选择器。

 

方法有

Js延迟加载

Ready     $(document).ready(function(){

            // 在这里写你的代码...

});

$(functoin(){

 

})

 

 

事件有

Click     $(‘div’).click(functoin(){

               Alert(1)

})

Dblclick   ,   mousedown  mouseup ,  mouseover , mousemove  mouseout  mousemove keypress   keydown keyup  change  reset  submit  hover

 

效果有

Show  hide   toggle

 

 

Css 有

Css   offset  width  height  position

 

属性有

Attr  val  html  addClass   removeAttr

 

筛选有

Eq   find    index  get   first  lastss

 

动画有

Animate  stop

 

文档处理有

Append  remove  empty

 

工具方法有

Trim  ajax  setPage(分页) extend inArray   parseJSON   isFunction   isEmpty

isNumeric  type

 

 

cq核心源码

 

  1 /*
  2   作者:姚观寿
  3   cq:类似于jq的一个小型库
  4   时间:2016.6.19
  5   
  6 */
  7 (function(window,undefined,document){
  8    var isIe678   =   (navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion .split(";")[1].replace(/[ ]/g,"")=="MSIE6.0")||
  9                            (navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion .split(";")[1].replace(/[ ]/g,"")=="MSIE7.0")||
 10                            (navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion .split(";")[1].replace(/[ ]/g,"")=="MSIE8.0");
 11  
 12  function checkType(data_type){
 13        return  Object.prototype.toString.call(data_type);
 14      }    
 15 
 16  function myAddEvent(obj , sEv , fn){
 17    try{  // Chrome、FireFox、Opera、Safari、IE9.0及其以上版本
 18          obj.addEventListener(sEv,fn,false);
 19      }catch(e){
 20         try{  // IE8.0及其以下版本
 21                  obj.attachEvent(‘on‘ + sEv ,function(){
 22                           fn.call(obj);  
 23                     });
 24         }catch(e){  
 25                               // 早期浏览器
 26                            obj[‘on‘ + sEv] = fn;
 27          } 
 28     }
 29  } 
 30  
 31   function getTopOrLeft(obj,attr){
 32              var obj_attr = 0;
 33              while(obj){
 34                    obj_attr+=obj[attr];
 35                   obj=obj.offsetParent;
 36              }
 37              return   obj_attr;
 38           }  
 39  
 40  function getStyle(obj , attr){
 41         var new_attr;
 42       if(attr==‘opacity‘){
 43                  new_attr =  parseFloat((window.getComputedStyle?getComputedStyle(obj,null)[attr]:obj.currentStyle[attr]));  
 44            }else{
 45                 new_attr =   parseInt(window.getComputedStyle?getComputedStyle(obj,null)[attr]:obj.currentStyle[attr]);  
 46                } 
 47               if(isNaN(new_attr)){
 48                      new_attr = 0;
 49                   }
 50       return   new_attr;
 51  /* return  attr==‘opacity‘?parseFloat((window.getComputedStyle?getComputedStyle(obj,null)[attr]:obj.currentStyle[attr])):parseInt(window.getComputedStyle?getComputedStyle(obj,null)[attr]:obj.currentStyle[attr]);     */
 52 }
 53 
 54 function forEach(obj , fn ){
 55     var i=0, len = obj.length;
 56     for(;i<len;i++){
 57            fn(i);
 58     }
 59 }
 60  function getByClassName(oParent,className){
 61          var  aEle = oParent.getElementsByTagName(‘*‘),
 62                 aResult = [];
 63              forEach(aEle,function(i){
 64                  if(aEle[i].className == className ){
 65                           aResult.push(aEle[i]); 
 66                     }
 67             }); 
 68             return  aResult;     
 69     }
 70 
 71 function CopyArr(arr){
 72           var newArr = [];
 73              forEach(arr , function( i ){
 74                         newArr.push(arr[i]);               
 75                     }); 
 76          return       newArr;
 77     }
 78 
 79 function getIndex( obj ){
 80  var sibing = obj.parentNode.children,
 81         index = null ;
 82         forEach(sibing , function(i){
 83                if(sibing[i] == obj ){
 84                   return  index = i-1;
 85                 }  
 86          });
 87          return index;
 88 }
 89  
 90 function Tween(value, prop, animation_attr) {
 91     //初始化
 92      this.elem    = animation_attr.elem;
 93     this.prop    = prop;
 94     this.easing  = "swing"; //动画缓动算法
 95     this.options = animation_attr.options;
 96      this.start   = this.now = this.get();
 97      this.end     = value;
 98      this.unit    = "px"
 99 }
100 
101 Tween.prototype = {
102      get: function() {
103         var computed = getStyle(this.elem, this.prop);
104          return parseFloat(computed);
105     },
106      run:function(percent){
107          var eased;
108          this.pos = eased = swing(percent);
109           this.now = (this.end - this.start) * eased + this.start;
110         
111           this.elem.style[this.prop] = this.now +this.unit;
112         return this;
113     }
114 }
115  
116  //动画算法
117 function swing(p) {
118      var tmpe = 0.5 - Math.cos(p * Math.PI) / 2; 
119      return tmpe
120 }
121 
122  Tween.prototype = {
123      get: function() {
124         var computed = getStyle(this.elem, this.prop);
125          return parseFloat(computed);
126     },
127      run:function(percent){
128          var eased;
129          this.pos = eased = swing(percent);
130           this.now = (this.end - this.start) * eased + this.start;
131      
132         if(this.prop=="opacity"){
133                          if(isIe678){
134                                  this.elem.style.filter=‘alpha(opacity:‘+(this.now*100)+‘)‘
135                             }else{
136                                 this.elem.style[this.prop] = this.now;
137                             }
138              }else{
139                   this.elem.style[this.prop] = this.now +this.unit;
140         }
141         return this;
142     }
143 }
144 
145  function AnimationFn(elem, properties, options,  fn){
146  /*    elem.timerId = null;
147      if (elem.timerId !=undefined && elem.timerId) {
148             return false;
149          }*/
150  
151      var animation_attr = {
152          elem            : elem,
153         props           : properties,
154         originalOptions : options,
155         options         : options,
156         startTime       : null,//动画开始时间
157         tweens          : []//存放每个属性的缓动对象,用于动画
158      }
159   
160     for (var k in properties) {
161           animation_attr.tweens.push( new Tween(properties[k], k, animation_attr));
162     }
163      animation_attr.startTime=AnimationFn.fxNow || createFxNow();
164      var tick = function() {
165          var currentTime = AnimationFn.fxNow || createFxNow();
166              remaining = Math.max(0, animation_attr.startTime + animation_attr.options.duration - currentTime),
167              temp = remaining / animation_attr.options.duration || 0,
168              percent = 1 - temp;
169          var index = 0,
170             length = animation_attr.tweens.length;
171           for (; index < length; index++) {
172               animation_attr.tweens[index].run(percent);
173         }
174 
175          if (percent <= 1 && length) {
176              return remaining;
177          } else {
178               return false;
179         }
180 
181     }
182      tick.elem = elem;
183     //tick.anim = animation_attr;
184       tick.fn  = fn;
185        AnimationFn.fx.timer(tick);
186 }    
187 
188  function createFxNow() {
189     setTimeout(function() {
190          AnimationFn.fxNow = undefined;
191     },0);
192      return (AnimationFn.fxNow = Date.now());
193 }
194    
195 AnimationFn.fx = {
196      timer: function(timer) {
197           AnimationFn.timer=timer;
198          if (timer()) {  //timer() 只是调用一个而已,就是说有这个动画时候就执行函数 返回一个false 或者是 remaining;
199             //开始执行动画 走这里
200             AnimationFn.fx.start();
201         }  
202     },
203      start: function() {
204         if (!AnimationFn.timer.elem.timerId) {
205              AnimationFn.timer.elem.timerId = setInterval(AnimationFn.fx.tick, 13);
206         }
207     },
208      stop:function(){
209       clearInterval(AnimationFn.timer.elem.timerId);
210           AnimationFn.timer.elem.timerId = null;
211            AnimationFn.timer.fn&&AnimationFn.timer.fn.call(AnimationFn.timer.elem );
212      },
213      tick: function() {
214         //不停的调用,直到定时器关闭
215           var timer,
216             i = 0;
217           AnimationFn.fxNow = Date.now();
218          if (!AnimationFn.timer()) {
219               AnimationFn.fx.stop();
220          }
221           AnimationFn.fxNow = undefined;
222     }
223 }
224  
225 function CQuery(vArg,chained_mode){
226  
227             this.elements = [];
228          switch(typeof vArg) {
229               case  ‘function‘:
230              
231                           myAddEvent(window , ‘load‘ , vArg);
232                         break;
233               case ‘string‘:
234                             switch(vArg.charAt(0)){
235                                    case ‘#‘:    //id
236                                         var obj = document.getElementById(vArg.substring(1));
237                                             this.elements.push(obj);
238                                           break;
239                                   case ‘.‘:    //class
240                                           var objs = getByClassName(document , vArg.substring(1));
241                                             this.elements = objs;
242                                           break; 
243                                  default:   //tagName
244                                            this.elements = document.getElementsByTagName(vArg);
245                                            break;
246                                }
247                        break;  
248                      
249                 case  ‘object‘:
250                        switch(checkType(vArg)){
251                                 case  "[object HTMLDocument]":
252                                           // this.elements =  window;
253                                           this.elements.push(window);
254                                           break;
255                                  default :       
256                                             this.elements.push(vArg);  break;
257                            }
258                   
259     }
260      return this === window&&new CQuery(vArg);
261  }
262  
263  CQuery.prototype = {
264               ev:function(event , fn){
265                    var this_elements = this.elements;
266                     forEach(this.elements,function(i){
267                             myAddEvent(this_elements[i] , event , fn);   
268                       });  
269                     new_CQuery.elements = this.elements;
270                     return new_CQuery;  
271             },
272             ready:function(fn){
273                    
274                        myAddEvent(window, ‘load‘ , fn);
275               },
276              click:function( fn ){
277                  return this.ev(‘click‘,fn);
278             },
279            dblclick : function( fn ){
280                   return this.ev(‘dblclick‘,fn);
281                },
282            mousedown : function( fn ){
283                   return this.ev(‘mousedown‘,fn);
284                },  
285            mouseup : function( fn ){
286                    return this.ev(‘mouseup‘,fn);
287                },
288            mouseover : function( fn ){
289                  return this.ev(‘mouseover‘,fn);
290                }, 
291            mousemove : function( fn ){
292                  return this.ev(‘mousemove‘,fn);
293                },  
294            mouseout : function ( fn ){
295                   return this.ev(‘mouseout‘,fn);
296                },  
297            mousemove:function(fn){
298                return  this.ev(‘mousemove‘,fn);
299             },
300            keypress:function( fn ){
301                return  this.ev(‘keypress‘,fn);
302             },
303            keydown : function( fn ){
304                  return  this.ev(‘keydown‘,fn); 
305                },
306           keyup : function( fn ){
307                  return  this.ev(‘keyup‘,fn); 
308                },
309            change : function( fn ){
310                  return  this.ev(‘change‘,fn); 
311                },    
312            reset : function( fn ){
313                  return  this.ev(‘reset‘,fn); 
314                },    
315            submit : function( fn ){
316                  return  this.ev(‘submit‘,fn); 
317                },    
318             show:function(){
319                  var this_elements=this.elements;
320                 forEach(this.elements,function(i){
321                       this_elements[i].style.display = ‘block‘;
322                 });  
323                    new_CQuery.elements =  this.elements;
324                     return new_CQuery; 
325            },
326            hide:function(){
327                  var this_elements = this.elements ;
328                   forEach(this.elements,function(i){
329                        this_elements[i].style.display = ‘none‘;
330                 });  
331                  new_CQuery.elements =  this.elements;
332                   return new_CQuery;  
333            },
334            hover:function(fnOver , fnOut){
335                  var this_elements = this.elements ;
336                forEach(this.elements,function(i){
337                     myAddEvent(this_elements[i] , ‘mouseover‘ , fnOver);
338                     myAddEvent(this_elements[i] , ‘mouseout‘ , fnOut);    
339                });
340                  new_CQuery.elements =  this.elements;
341                   return new_CQuery; 
342            },
343            css:function(attr , value){
344               if(arguments.length==2){  //设置样式
345                  var  this_elements = this.elements
346                    forEach(this.elements , function(i){
347                                if(attr!=‘opacity‘){
348                                       this_elements[i].style[attr] = value; 
349                                  }else{
350                                       this_elements[i].style[attr] = value;
351                                  }
352                     });  
353               }else{   //获取样式
354                        return     getStyle(this.elements[0] , attr);
355               }
356                      new_CQuery.elements =  this.elements;
357                     return new_CQuery; 
358               },
359            toggle:function(){ 
360                      var  argm = arguments,
361                           argmLen = arguments.length,
362                           this_elements = this.elements ;
363                       forEach(this.elements,function(i){
364                                            var count = 0;              
365                                           myAddEvent(this_elements[i] , ‘click‘ , function(){
366                                            argm[count++%argmLen].call(this);
367                                                                                       })    ;
368                                     });   
369                     new_CQuery.elements =  this.elements;
370                      return new_CQuery; 
371                },
372                attr:function( attr , value){
373                          var    this_elements = this.elements ;
374                            if(arguments.length==2){
375                               forEach(this.elements , function( i ){
376                                         this_elements[i][attr] =  value;
377                              });
378                               new_CQuery.elements =  this.elements;
379                                return new_CQuery; 
380                           }else{
381                                           return this.elements[0][attr];
382                           }
383                },
384                eq:function( n ){
385                    return $(this.elements[n]); 
386                },
387                 find:function(str){
388                       var  aResult = [] ,
389                              this_elements = this.elements;
390                       forEach(this.elements , function( i ){
391                                       switch(str.charAt(0)){
392                                             case ‘.‘ :  //class
393                                                   var aEle = getByClassName(this.elements[i] , str.substring(1));
394                                                   aResult = aResult.concat(aEle);
395                                                   break;
396                                            default :
397                                                 var aEle = this_elements[i].getElementsByTagName(str);
398                                                        aResult = aResult.concat(CopyArr(aEle));
399                                           }
400                              }); 
401                      new_CQuery.elements = aResult;
402                     return new_CQuery;  
403                    },
404                    index : function(){
405                          return getIndex(this.elements[0]);
406                    },
407 
408                    offset:function(){
409          
410                                  if(arguments.length==0){
411                                    var offset={
412                                                          top:getTopOrLeft(this.elements[0],‘top‘),
413                                                          left:getTopOrLeft(this.elements[0],‘left‘)
414                                                       }
415                                     return      offset;                  
416                                 }else{
417                                            var this_elements = this.elements ;
418                                            forEach(this.elements,function(i){
419                                                      this_elements[i].style.left = arguments.length[0].left;
420                                                       this_elements[i].style.top = arguments.length[0].top;
421                                            });
422                                              new_CQuery.elements =  this.elements;
423                                              return new_CQuery;  
424                                          
425                                      }
426                                     
427                        },
428                       position:function(){
429                                  if(arguments.length==0){
430                                    var offset={
431                                                          top:this.elements[0].offsetTop,
432                                                          left:this.elements[0].offsetLeft
433                                                       }
434                                     return      offset;                  
435                                 }else{
436                                            var this_elements = this.elements ;
437                                            forEach(this.elements,function(i){
438                                                      this_elements[i].style.left = arguments.length[0].left;
439                                                       this_elements[i].style.top = arguments.length[0].top;
440                                            });
441                                              new_CQuery.elements =  this.elements;
442                                              return new_CQuery;  

以上是关于一个类似于jq的小型库的主要内容,如果未能解决你的问题,请参考以下文章

十条jQuery代码片段助力Web开发效率提升

原生封装一个类似于JQ的ajax方法

Chrome-Devtools代码片段中的多个JS库

java 一个类似于tic tac toe的小型Java游戏

类似于过去访问的小型独立 SQL 数据库(即文件数据库)

BottomNavigationView 滞后于片段事务