JS怎么仿JQuery选择器功能

JS怎么仿JQuery选择器功能

这篇文章主要介绍了JS怎么仿JQuery选择器功能的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇JS怎么仿JQuery选择器功能文章都会有所收获,下面我们一起来看看吧。

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

JS怎么仿JQuery选择器功能

functionZQuery(arg){this.elements=[];//存东西this.domString='';//保存字符串标签if(typeofarg=='function'){//DOMReadyDOMReady(arg);}elseif(typeofarg=='string'||arginstanceofString){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(vari=0;i<this.elements.length;i++){this.elements[i].style[name]=value;}}else{if(typeofname=='string'){//获取样式returngetStyle(this.elements[0],name);}else{//批量设置样式varjson=name;for(varnameinjson){for(vari=0;i<this.elements.length;i++){this.elements[i].style[name]=json[name];}}}}};ZQuery.prototype.attr=function(name,value){if(arguments.length==2){//设置一个属性for(vari=0;i<this.elements.length;i++){this.elements[i].setAttribute(name,value);}}else{if(typeofname=='string'){//获取属性returnthis.elements[0].getAttribute(name);}else{//批量设置属性varjson=name;for(varnameinjson){for(vari=0;i<this.elements.length;i++){this.elements[i].setAttribute(name,json[name]);}}}}};ZQuery.prototype.addClass=function(sClass){varre=newRegExp('\\b'+sClass+'\\b','g');for(vari=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,'');}returnthis;};ZQuery.prototype.removeClass=function(sClass){varre=newRegExp('\\b'+sClass+'\\b','g');for(vari=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');}}}returnthis;};ZQuery.prototype.html=function(value){if(value||value==''){//设置for(vari=0;i<this.elements.length;i++){this.elements[i].innerHTML=value;}}else{returnthis.elements[0].innerHTML;}};ZQuery.prototype.val=function(value){if(value||value==''){//设置for(vari=0;i<this.elements.length;i++){this.elements[i].value=value;}}else{returnthis.elements[0].value;}};ZQuery.prototype.show=function(){for(vari=0;i<this.elements.length;i++){this.elements[i].style.display='block';}returnthis;};ZQuery.prototype.hide=function(){for(vari=0;i<this.elements.length;i++){this.elements[i].style.display='none';}returnthis;};;'clickmouseovermouseoutmousedownmouseupmousemovemouseentermouseleavechangekeydownkeyupcontextmenu'.replace(/\w+/g,function(str){ZQuery.prototype[str]=function(fn){for(vari=0;i<this.elements.length;i++){addEvent(this.elements[i],str,fn);}};});ZQuery.prototype.get=function(n){for(vari=0;i<this.elements.length;i++){if(i==n){returnthis.elements[i];}}};ZQuery.prototype.eq=function(n){for(vari=0;i<this.elements.length;i++){if(i==n){return$(this.elements[i]);}}};ZQuery.prototype.index=function(){varaSiblings=this.elements[0].parentNode.children;for(vari=0;i<aSiblings.length;i++){if(aSiblings[i]==this.elements[0]){returni;}}};ZQuery.prototype.hover=function(fn1,fn2){for(vari=0;i<this.elements.length;i++){$(this.elements[i]).mouseenter(fn1);$(this.elements[i]).mouseleave(fn2);}};ZQuery.prototype.toggle=function(){varargs=arguments;var_this=this;for(vari=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(vari=0;i<this.elements.length;i++){move(this.elements[i],json,options);}};ZQuery.prototype.appendTo=function(arg){varaParent=$(arg);for(vari=0;i<aParent.length;i++){aParent.get(i).insertAdjacentHTML('beforeEnd',this.domString);}returnthis;};ZQuery.prototype.prependTo=function(arg){varaParent=$(arg);for(vari=0;i<aParent.length;i++){aParent.get(i).insertAdjacentHTML('afterBegin',this.domString);}returnthis;};ZQuery.prototype.insertAfter=function(arg){varaParent=$(arg);for(vari=0;i<aParent.length;i++){aParent.get(i).insertAdjacentHTML('afterEnd',this.domString);}returnthis;};ZQuery.prototype.insertBefore=function(arg){varaParent=$(arg);for(vari=0;i<aParent.length;i++){aParent.get(i).insertAdjacentHTML('beforeBegin',this.domString);}returnthis;};ZQuery.prototype.remove=function(){varoParent=this.elements[0].parentNode;for(vari=0;i<this.elements.length;i++){oParent.removeChild(this.elements[i]);}returnthis;};function$(arg){returnnewZQuery(arg);};$.ajax=function(json){ajax(json);};$.jsonp=function(json){jsonp(json);};$.fn=ZQuery.prototype;$.fn.extend=function(json){for(varnameinjson){ZQuery.prototype[name]=json[name];}};functionjson2url(json){vararr=[];for(varnameinjson){arr.push(name+'='+encodeURIComponent(json[name]));}returnarr.join('&');}functionajax(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){varoAjax=newXMLHttpRequest();}else{varoAjax=newActiveXObject('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);}}};}functionjsonp(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);}varoHead=document.getElementsByTagName('head')[0];varoS=document.createElement('script');oS.src=json.url+'?'+json2url(json.data);oHead.appendChild(oS);}functiongetStyle(obj,sName){return(obj.currentStyle||getComputedStyle(obj,false))[sName];}functionaddEvent(obj,sEv,fn){if(obj.addEventListener){obj.addEventListener(sEv,function(ev){varoEvent=ev||event;if(fn.call(obj,oEvent)==false){oEvent.cancelBubble=true;oEvent.preventDefault&&oEvent.preventDefault();}},false);}else{obj.attachEvent('on'+sEv,function(){varoEvent=ev||event;if(fn.call(obj,oEvent)==false){oEvent.cancelBubble=true;returnfalse;}});}}functionDOMReady(fn){if(document.addEventListener){addEvent(document,'DOMContentLoaded',function(){fn&&fn();});}else{addEvent(document,'onreadystatechange',function(){if(document.readyState=='complete'){fn&&fn();}});}}functiongetByClass(oParent,sClass){if(oParent.getElementsByClassName){returnoParent.getElementsByClassName(sClass);}else{varaResult=[];varaEle=oParent.getElementsByTagName('*');varre=newRegExp('\\b'+sClass+'\\b','g');for(vari=0;i<aEle.length;i++){if(aEle[i].className.search(re)!=-1){aResult.push(aEle[i]);}}returnaResult;}}functiongetByStr(aParent,str){varaChild=[];//遍历父级for(vari=0;i<aParent.length;i++){switch(str.charAt(0)){case'#'://#idaChild.push(document.getElementById(str.substring(1)));break;case'.'://.classvaraEle=getByClass(aParent[i],str.substring(1));for(varj=0;j<aEle.length;j++){aChild.push(aEle[j]);}break;default:if(/^\w+\.\w+$/.test(str)){//筛选//li.onvararr=str.split('.');varre=newRegExp('\\b'+arr[1]+'\\b','g');varaEle=aParent[i].getElementsByTagName(arr[0]);for(varj=0;j<aEle.length;j++){if(aEle[j].className.search(re)!=-1){aChild.push(aEle[j]);}}}elseif(/^\w+\[\w+\=\w+\]$/.test(str)){//属性vararr=str.split(/\[|\=|\]/);varaEle=aParent[i].getElementsByTagName(arr[0]);for(varj=0;j<aEle.length;j++){if(aEle[j].getAttribute(arr[1])==arr[2]){aChild.push(aEle[j]);}}}elseif(/^\w+\:\w+(\(\d+\))?$/.test(str)){vararr=str.split(/\:|\(|\)/);varaEle=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(varj=0;j<aEle.length;j+=2){aChild.push(aEle[j]);}break;case'odd':for(varj=1;j<aEle.length;j+=2){aChild.push(aEle[j]);}break;case'eq':aChild.push(aEle[arr[2]]);break;case'lt':for(varj=0;j<arr[2];j++){aChild.push(aEle[j]);}break;case'gt':for(varj=parseInt(arr[2])+1;j<aEle.length;j++){aChild.push(aEle[j]);}break;}}else{//标签varaEle=aParent[i].getElementsByTagName(str);for(varj=0;j<aEle.length;j++){aChild.push(aEle[j]);}}break;}}returnaChild;}functiongetEle(str){vararr=str.replace(/^\s+|\s+$/g,'').split(/\s+/);varaParent=[document];varaChild=[];for(vari=0;i<arr.length;i++){aChild=getByStr(aParent,arr[i]);//这一次获取到的子级,是下一次获取的父级aParent=aChild;}returnaChild;}functionmove(obj,json,options){clearInterval(obj.timer);options=options||{};options.easing=options.easing||'ease-out';options.duration=options.duration||800;varcount=Math.floor(options.duration/30);varstart={};vardis={};for(varnameinjson){start[name]=parseFloat(getStyle(obj,name));dis[name]=json[name]-start[name];}varn=0;obj.timer=setInterval(function(){n++;for(varnameinjson){switch(options.easing){case'linear':vara=n/count;varcur=start[name]+dis[name]*a;break;case'ease-in':vara=n/count;varcur=start[name]+dis[name]*a*a*a;break;case'ease-out':vara=1-n/count;varcur=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);}

关于“JS怎么仿JQuery选择器功能”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“JS怎么仿JQuery选择器功能”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注恰卡编程网行业资讯频道。

发布于 2022-03-29 22:26:15
收藏
分享
海报
0 条评论
30
上一篇:怎么学好单片机 下一篇:PCB叠层设计的规则是什么
目录

    0 条评论

    本站已关闭游客评论,请登录或者注册后再评论吧~

    忘记密码?

    图形验证码