欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JS仿JQuery选择器功能

程序员文章站 2023-11-29 13:36:52
jquery作为应用最广的js库,其最强大的功能之一就是几乎涵盖所有方法的且代码十分简短的选择器功能,我们也可用自己的代码实现此功能,代码逻辑、使用方法与jquery一致...

jquery作为应用最广的js库,其最强大的功能之一就是几乎涵盖所有方法的且代码十分简短的选择器功能,我们也可用自己的代码实现此功能,代码逻辑、使用方法与jquery一致

function zquery(arg){
 this.elements = [];  //存东西
 this.domstring = '';  //保存字符串标签
 if(typeof arg=='function'){
 //domready
 domready(arg);
 }else if(typeof arg=='string'||arg instanceof string){
 if(arg.indexof('<')!=-1){
  this.domstring = arg;
 }else{
  //获取元素
  this.elements = getele(arg);
  this.length = this.elements.length;
 }
 }else{
 //原生对象-》zquery对象
 this.elements.push(arg);
 this.length = this.elements.length;
 }
}
zquery.prototype.css = function(name,value){
 if(arguments.length==2){
  //设置一个样式
  for(var i=0;i<this.elements.length;i++){
  this.elements[i].style[name] = value;
  }
 }else{
  if(typeof name=='string'){
  //获取样式
  return getstyle(this.elements[0],name);
  }else{
  //批量设置样式
  var json = name;
  for(var name in json){
   for(var i=0;i<this.elements.length;i++){
   this.elements[i].style[name] = json[name];
   }
  }
  }
 }
};
zquery.prototype.attr = function(name,value){
 if(arguments.length==2){
  //设置一个属性
  for(var i=0;i<this.elements.length;i++){
  this.elements[i].setattribute(name,value);
  }
 }else{
  if(typeof name=='string'){
  //获取属性
  return this.elements[0].getattribute(name);
  }else{
  //批量设置属性
  var json = name;
  for(var name in json){
   for(var i=0;i<this.elements.length;i++){
   this.elements[i].setattribute(name,json[name]);
   }
  }
  }
 }
};
zquery.prototype.addclass = function(sclass){
 var re = new regexp('\\b'+sclass+'\\b','g');
 for(var i=0;i<this.elements.length;i++){
 if(this.elements[i].classname){
  if(this.elements[i].classname.search(re)==-1){
  this.elements[i].classname += ' '+sclass;
  }
 }else{
  this.elements[i].classname = sclass;
 }
 this.elements[i].classname = this.elements[i].classname.replace(/^\s+|\s+$/g,'').replace(/\s+/g,' ');
 }
 return this;
};
zquery.prototype.removeclass = function(sclass){
 var re = new regexp('\\b'+sclass+'\\b','g');
 for(var i=0;i<this.elements.length;i++){
 if(this.elements[i].classname){
  this.elements[i].classname = this.elements[i].classname.replace(re,'');
  this.elements[i].classname = this.elements[i].classname.replace(/^\s+|\s+$/g,'').replace(/\s+/g,' ');
  if(this.elements[i].classname==''){
  this.elements[i].removeattribute('class');
  }
 }
 }
 return this;
};
zquery.prototype.html = function(value){
 if(value||value==''){
 //设置
 for(var i=0;i<this.elements.length;i++){
  this.elements[i].innerhtml = value;
 } 
 }else{
 return this.elements[0].innerhtml;
 }
};
zquery.prototype.val = function(value){
 if(value||value==''){
 //设置
 for(var i=0;i<this.elements.length;i++){
  this.elements[i].value = value;
 } 
 }else{
 return this.elements[0].value;
 }
};
zquery.prototype.show = function(){
 for(var i=0;i<this.elements.length;i++){
 this.elements[i].style.display = 'block';
 }
 return this;
};
zquery.prototype.hide = function(){
 for(var i=0;i<this.elements.length;i++){
 this.elements[i].style.display = 'none';
 }
 return this;
};
;'click mouseover mouseout mousedown mouseup mousemove mouseenter mouseleave change keydown keyup contextmenu'.replace(/\w+/g,function(str){
 zquery.prototype[str] = function(fn){
 for(var i=0;i<this.elements.length;i++){
  addevent(this.elements[i],str,fn);
 }
 };
});
zquery.prototype.get = function(n){
 for(var i=0;i<this.elements.length;i++){
 if(i==n){
  return this.elements[i];
 }
 }
};
zquery.prototype.eq = function(n){
 for(var i=0;i<this.elements.length;i++){
 if(i==n){
  return $(this.elements[i]);
 }
 }
};
zquery.prototype.index = function(){
 var asiblings = this.elements[0].parentnode.children;
 for(var i=0;i<asiblings.length;i++){
 if(asiblings[i]==this.elements[0]){
  return i;
 }
 }
};
zquery.prototype.hover = function(fn1,fn2){
 for(var i=0;i<this.elements.length;i++){
 $(this.elements[i]).mouseenter(fn1);
 $(this.elements[i]).mouseleave(fn2);
 }
};
zquery.prototype.toggle = function(){
 var args = arguments;
 var _this = this;
 for(var i=0;i<this.elements.length;i++){
 ;(function(count){
  $(_this.elements[i]).click(function(ev){
  args[count%args.length].call(this,ev);
  count++;
  });
 })(0);
 }
};
zquery.prototype.animate = function(json,options){
 for(var i=0;i<this.elements.length;i++){
 move(this.elements[i],json,options);
 }
};
zquery.prototype.appendto = function(arg){
 var aparent = $(arg);
 for(var i=0;i<aparent.length;i++){
 aparent.get(i).insertadjacenthtml('beforeend',this.domstring);
 }
 return this;
};
zquery.prototype.prependto = function(arg){
 var aparent = $(arg);
 for(var i=0;i<aparent.length;i++){
 aparent.get(i).insertadjacenthtml('afterbegin',this.domstring);
 }
 return this;
};
zquery.prototype.insertafter = function(arg){
 var aparent = $(arg);
 for(var i=0;i<aparent.length;i++){
 aparent.get(i).insertadjacenthtml('afterend',this.domstring);
 }
 return this;
};
zquery.prototype.insertbefore = function(arg){
 var aparent = $(arg);
 for(var i=0;i<aparent.length;i++){
 aparent.get(i).insertadjacenthtml('beforebegin',this.domstring);
 }
 return this;
};
zquery.prototype.remove = function(){
 var oparent = this.elements[0].parentnode;
 for(var i=0;i<this.elements.length;i++){
 oparent.removechild(this.elements[i]);
 }
 return this;
};
function $(arg){
 return new zquery(arg);
};
$.ajax = function(json){
 ajax(json);
};
$.jsonp = function(json){
 jsonp(json);
};
$.fn = zquery.prototype;
$.fn.extend = function(json){
 for(var name in json){
 zquery.prototype[name] = json[name];
 }
};
function json2url(json){
 var arr = [];
 for(var name in json){
 arr.push(name+'='+encodeuricomponent(json[name]));
 }
 return arr.join('&');
}
function ajax(json){
 json = json||{};
 if(!json.url)return;
 json.type = json.type||'get';
 json.timeout = json.timeout||15000;
 json.data = json.data||{};
 json.data.t = math.random();
 if(window.xmlhttprequest){
 var oajax = new xmlhttprequest();
 }else{
 var oajax = new activexobject('microsoft.xmlhttp');
 }
 switch(json.type.tolowercase()){
 case 'get':
  oajax.open('get',json.url+'?'+json2url(json.data),true);
  oajax.send();
  break;
 case 'post':
  oajax.open('post',json.url,true);
  oajax.setrequestheader('content-type','application/x-www-form-urlencoded');
  oajax.send(json2url(json.data));
  break;
 default:
  oajax.open('get',json.url+'?'+json2url(json.data),true);
  oajax.send();
  break;
 }
 json.loading&&json.loading();
 json.timer = settimeout(function(){
 oajax.onreadystatechange = null;
 json.error&&json.error('网络超时。');
 },json.timeout);

 oajax.onreadystatechange = function(){
 if(oajax.readystate==4){
  cleartimeout(json.timer);
  if(oajax.status>=200&&oajax.status<300||oajax.status==304){
  json.success&&json.success(oajax.responsetext);
  }else{
  json.error&&json.error(oajax.status);
  }
 }
 };
}
function jsonp(json){
 json = json||{};
 if(!json.url)return;
 json.timeout = json.timeout||15000;
 json.cbname = json.cbname||'cb';
 json.data = json.data||{};
 json.data[json.cbname] = 'show'+math.random();
 json.data[json.cbname] = json.data[json.cbname].replace('.','');
 json.timer = settimeout(function(){
 window[json.data[json.cbname]] = function(res){
  ohead.removechild(os);
  json.error&&json.error('网络超时!');
 }
 },json.timeout);
 window[json.data[json.cbname]] = function(res){
 cleartimeout(json.timer);
 ohead.removechild(os);
 json.success&&json.success(res);
 }
 var ohead = document.getelementsbytagname('head')[0];
 var os = document.createelement('script');
 os.src = json.url+'?'+json2url(json.data);
 ohead.appendchild(os);
}
function getstyle(obj,sname){
 return (obj.currentstyle||getcomputedstyle(obj,false))[sname];
}
function addevent(obj,sev,fn){
 if(obj.addeventlistener){
 obj.addeventlistener(sev,function(ev){
  var oevent = ev||event;
  if(fn.call(obj,oevent)==false){
  oevent.cancelbubble = true;
  oevent.preventdefault&&oevent.preventdefault();
  }
 },false);
 }else{
 obj.attachevent('on'+sev,function(){
  var oevent = ev||event;
  if(fn.call(obj,oevent)==false){
  oevent.cancelbubble = true;
  return false;
  }
 });
 }
}
function domready(fn){
 if(document.addeventlistener){
 addevent(document,'domcontentloaded',function(){
  fn&&fn();
 });
 }else{
 addevent(document,'onreadystatechange',function(){
  if(document.readystate=='complete'){
  fn&&fn();
  }
 });
 }
}
function getbyclass(oparent,sclass){
 if(oparent.getelementsbyclassname){
 return oparent.getelementsbyclassname(sclass);
 }else{
 var aresult = [];
 var aele = oparent.getelementsbytagname('*');
 var re = new regexp('\\b'+sclass+'\\b','g');
 for(var i=0;i<aele.length;i++){
  if(aele[i].classname.search(re)!=-1){
  aresult.push(aele[i]);
  }
 }
 return aresult;
 }
}
function getbystr(aparent,str){
 var achild = [];
 //遍历父级
 for(var i=0;i<aparent.length;i++){
 switch(str.charat(0)){
  case '#':
  //#id
  achild.push(document.getelementbyid(str.substring(1)));
  break;
  case '.':
  //.class
  var aele = getbyclass(aparent[i],str.substring(1));
  for(var j=0;j<aele.length;j++){
   achild.push(aele[j]);
  }
  break;
  default:
  if(/^\w+\.\w+$/.test(str)){
   //筛选
   //li.on
   var arr = str.split('.');
   var re = new regexp('\\b'+arr[1]+'\\b','g');
   var aele = aparent[i].getelementsbytagname(arr[0]);
   for(var j=0;j<aele.length;j++){
   if(aele[j].classname.search(re)!=-1){
    achild.push(aele[j]);
   }
   }
  }else if(/^\w+\[\w+\=\w+\]$/.test(str)){
   //属性
   var arr = str.split(/\[|\=|\]/);
   var aele = aparent[i].getelementsbytagname(arr[0]);
   for(var j=0;j<aele.length;j++){
   if(aele[j].getattribute(arr[1]) == arr[2]){
    achild.push(aele[j]);
   }
   }
  }else if(/^\w+\:\w+(\(\d+\))?$/.test(str)){
   var arr = str.split(/\:|\(|\)/);
   var aele = aparent[i].getelementsbytagname(arr[0]);
   switch(arr[1]){
   case 'first':
    achild.push(aele[0]);
    break;
   case 'last':
    achild.push(aele[aele.length-1]);
    break;
   case 'even':
    for(var j=0;j<aele.length;j+=2){
    achild.push(aele[j]);
    }
    break;
   case 'odd':
    for(var j=1;j<aele.length;j+=2){
    achild.push(aele[j]);
    }
    break;
   case 'eq':
    achild.push(aele[arr[2]]);
    break;
   case 'lt':
    for(var j=0;j<arr[2];j++){
    achild.push(aele[j]);
    }
    break;
   case 'gt':
    for(var j=parseint(arr[2])+1;j<aele.length;j++){
    achild.push(aele[j]);
    }
    break;
   }
  }else{
   //标签
   var aele = aparent[i].getelementsbytagname(str);
   for(var j=0;j<aele.length;j++){
   achild.push(aele[j]);
   }
  }
  break;
 }
 }
 return achild;
}
function getele(str){
 var arr = str.replace(/^\s+|\s+$/g,'').split(/\s+/);
 var aparent = [document];
 var achild = [];
 for(var i=0;i<arr.length;i++){
 achild = getbystr(aparent,arr[i]);
 //这一次获取到的子级,是下一次获取的父级
 aparent = achild;
 }
 return achild;
}
function move(obj,json,options){
 clearinterval(obj.timer); 
 options=options || {};
 options.easing=options.easing|| 'ease-out';
 options.duration=options.duration || 800;
 var count=math.floor(options.duration/30);
 var start={};
 var dis={};
 for(var name in json){
 start[name]=parsefloat(getstyle(obj,name));
 dis[name]=json[name]-start[name];
 }
 var n=0;
 obj.timer=setinterval(function(){
 n++;
 for(var name in json){
  switch(options.easing){
  case 'linear':
   var a=n/count;
   var cur=start[name]+dis[name]*a;
   break;
  case 'ease-in':
   var a=n/count;
   var cur=start[name]+dis[name]*a*a*a;
   break;
  case 'ease-out':
   var a=1-n/count;
   var cur=start[name]+dis[name]*(1-a*a*a);
   break;
  }
  if(name=='opacity'){
  obj.style.opacity=cur;
  obj.style.filter='alpha(opacity:'+cur*100+')'; 
  }else{
  obj.style[name]=cur+'px';
  }
 }
 if(n==count){
  clearinterval(obj.timer);
  options.complete && options.complete(); 
 }
 },30);
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!