discuz中用到的javascript函数解析 <font color=red>原创

      2019-12-08 11:23      编程语言
discuz中用到的js不论是多浏览器兼容性和实用性都是非常不错的,推荐大家看下

varlang=newArray();
varuserAgent=navigator.userAgent.toLowerCase();
varis_opera=userAgent.indexOf('opera')!=-1&&opera.version();
varis_moz=(navigator.product=='Gecko')&&userAgent.substr(userAgent.indexOf('firefox')+8,3);
varis_ie=(userAgent.indexOf('msie')!=-1&&!is_opera)&&userAgent.substr(userAgent.indexOf('msie')+5,3);

function$(id){
returndocument.getElementById(id);
}
//定义数组的push属性
Array.prototype.push=function(value){
this[this.length]=value;
returnthis.length;
}
//javascript全选函数
functioncheckall(form,prefix,checkall){
varcheckall=checkall?checkall:'chkall';
for(vari=0;i<form.elements.length;i++){
vare=form.elements[i];
if(e.name&&e.name!=checkall&&(!prefix||(prefix&&e.name.match(prefix)))){
e.checked=form.elements[checkall].checked;
}
}
}

functiondoane(event){
e=event?event:window.event;
if(is_ie){
e.returnValue=false;
e.cancelBubble=true;
}elseif(e){
e.stopPropagation();
e.preventDefault();
}
}

functionfetchCheckbox(cbn){
return$(cbn)&&$(cbn).checked==true?1:0;
}

functiongetcookie(name){
varcookie_start=document.cookie.indexOf(name);
varcookie_end=document.cookie.indexOf(";",cookie_start);
returncookie_start==-1?'':unescape(document.cookie.substring(cookie_start+name.length+1,(cookie_end>cookie_start?cookie_end:document.cookie.length)));
}

functionthumbImg(obj){
varzw=obj.width;
varzh=obj.height;
if(is_ie&&zw==0&&zh==0){
varmatches;
re=/width=(["']?)(\d+)(\1)/i;
matches=re.exec(obj.outerHTML);
zw=matches[2];
re=/height=(["']?)(\d+)(\1)/i;
matches=re.exec(obj.outerHTML);
zh=matches[2];
}
obj.resized=true;
obj.style.width=zw+'px';
obj.style.height='auto';
if(obj.offsetHeight>zh){
obj.style.height=zh+'px';
obj.style.width='auto';
}
if(is_ie){
varimgid='img_'+Math.random();
obj.id=imgid;
setTimeout('try{if($(\''+imgid+'\').offsetHeight>'+zh+'){$(\''+imgid+'\').style.height=\''+zh+'px\';$(\''+imgid+'\').style.width=\'auto\';}}catch(e){}',1000);
}
obj.onload=null;
}

functionimgzoom(obj){}

functionin_array(needle,haystack){
if(typeofneedle=='string'||typeofneedle=='number'){
for(variinhaystack){
if(haystack[i]==needle){
returntrue;
}
}
}
returnfalse;
}

functionsetcopy(text,alertmsg){
if(is_ie){
clipboardData.setData('Text',text);
alert(alertmsg);
}elseif(prompt('PressCtrl+CCopytoClipboard',text)){
alert(alertmsg);
}
}

functionisUndefined(variable){
returntypeofvariable=='undefined'?true:false;
}

functionmb_strlen(str){
varlen=0;
for(vari=0;i<str.length;i++){
len+=str.charCodeAt(i)<0||str.charCodeAt(i)>255?(charset=='utf-8'?3:2):1;
}
returnlen;
}

functionsetcookie(cookieName,cookieValue,seconds,path,domain,secure){
varexpires=newDate();
expires.setTime(expires.getTime()+seconds);
document.cookie=escape(cookieName)+'='+escape(cookieValue)
+(expires?';expires='+expires.toGMTString():'')
+(path?';path='+path:'/')
+(domain?';domain='+domain:'')
+(secure?';secure':'');
}

functionstrlen(str){
return(is_ie&&str.indexOf('\n')!=-1)?str.replace(/\r?\n/g,'_').length:str.length;
}

functionupdatestring(str1,str2,clear){
str2='_'+str2+'_';
returnclear?str1.replace(str2,''):(str1.indexOf(str2)==-1?str1+str2:str1);
}

functiontoggle_collapse(objname,noimg){
varobj=$(objname);
obj.style.display=obj.style.display==''?'none':'';
if(!noimg){
varimg=$(objname+'_img');
img.src=img.src.indexOf('_yes.gif')==-1?img.src.replace(/_no\.gif/,'_yes\.gif'):img.src.replace(/_yes\.gif/,'_no\.gif');
}
varcollapsed=getcookie('discuz_collapse');
collapsed=updatestring(collapsed,objname,!obj.style.display);
setcookie('discuz_collapse',collapsed,(collapsed?86400*30:-(86400*30*1000)));
}

functiontrim(str){
return(str+'').replace(/(\s+)$/g,'').replace(/^\s+/g,'');
}

function_attachEvent(obj,evt,func){
if(obj.addEventListener){
obj.addEventListener(evt,func,false);
}elseif(obj.attachEvent){
obj.attachEvent("on"+evt,func);
}
}

varjsmenu=newArray();
varctrlobjclassName;
jsmenu['active']=newArray();
jsmenu['timer']=newArray();
jsmenu['iframe']=newArray();

functioninitCtrl(ctrlobj,click,duration,timeout,layer){
if(ctrlobj&&!ctrlobj.initialized){
ctrlobj.initialized=true;
ctrlobj.unselectable=true;

ctrlobj.outfunc=typeofctrlobj.onmouseout=='function'?ctrlobj.onmouseout:null;
ctrlobj.onmouseout=function(){
if(this.outfunc)this.outfunc();
if(duration<3)jsmenu['timer'][ctrlobj.id]=setTimeout('hideMenu('+layer+')',timeout);
}

ctrlobj.overfunc=typeofctrlobj.onmouseover=='function'?ctrlobj.onmouseover:null;
ctrlobj.onmouseover=function(e){
doane(e);
if(this.overfunc)this.overfunc();
if(click){
clearTimeout(jsmenu['timer'][this.id]);
}else{
for(varidinjsmenu['timer']){
if(jsmenu['timer'][id])clearTimeout(jsmenu['timer'][id]);
}
}
}
}
}

functioninitMenu(ctrlid,menuobj,duration,timeout,layer,drag){
if(menuobj&&!menuobj.initialized){
menuobj.initialized=true;
menuobj.ctrlkey=ctrlid;
menuobj.onclick=ebygum;
menuobj.style.position='absolute';
if(duration<3){
if(duration>1){
menuobj.onmouseover=function(){
clearTimeout(jsmenu['timer'][ctrlid]);
}
}
if(duration!=1){
menuobj.onmouseout=function(){
jsmenu['timer'][ctrlid]=setTimeout('hideMenu('+layer+')',timeout);
}
}
}
menuobj.style.zIndex=50;
if(is_ie){
menuobj.style.filter+="progid:DXImageTransform.Microsoft.shadow(direction=135,color=#CCCCCC,strength=2)";
}
if(drag){
menuobj.onmousedown=function(event){try{menudrag(menuobj,event,1);}catch(e){}};
menuobj.onmousemove=function(event){try{menudrag(menuobj,event,2);}catch(e){}};
menuobj.onmouseup=function(event){try{menudrag(menuobj,event,3);}catch(e){}};
}
}
}

varmenudragstart=newArray();
functionmenudrag(menuobj,e,op){
if(op==1){
if(in_array(is_ie?event.srcElement.tagName:e.target.tagName,['TEXTAREA','INPUT','BUTTON','SELECT'])){
return;
}
menudragstart=is_ie?[event.clientX,event.clientY]:[e.clientX,e.clientY];
menudragstart[2]=parseInt(menuobj.style.left);
menudragstart[3]=parseInt(menuobj.style.top);
doane(e);
}elseif(op==2&&menudragstart[0]){
varmenudragnow=is_ie?[event.clientX,event.clientY]:[e.clientX,e.clientY];
menuobj.style.left=(menudragstart[2]+menudragnow[0]-menudragstart[0])+'px';
menuobj.style.top=(menudragstart[3]+menudragnow[1]-menudragstart[1])+'px';
doane(e);
}elseif(op==3){
menudragstart=[];
doane(e);
}
}

functionshowMenu(ctrlid,click,offset,duration,timeout,layer,showid,maxh,drag){
varctrlobj=$(ctrlid);
if(!ctrlobj)return;
if(isUndefined(click))click=false;
if(isUndefined(offset))offset=0;
if(isUndefined(duration))duration=2;
if(isUndefined(timeout))timeout=500;
if(isUndefined(layer))layer=0;
if(isUndefined(showid))showid=ctrlid;
varshowobj=$(showid);
varmenuobj=$(showid+'_menu');
if(!showobj||!menuobj)return;
if(isUndefined(maxh))maxh=400;
if(isUndefined(drag))drag=false;

if(click&&jsmenu['active'][layer]==menuobj){
hideMenu(layer);
return;
}else{
hideMenu(layer);
}

varlen=jsmenu['timer'].length;
if(len>0){
for(vari=0;i<len;i++){
if(jsmenu['timer'][i])clearTimeout(jsmenu['timer'][i]);
}
}

initCtrl(ctrlobj,click,duration,timeout,layer);
ctrlobjclassName=ctrlobj.className;
ctrlobj.className+='hover';
initMenu(ctrlid,menuobj,duration,timeout,layer,drag);

menuobj.style.display='';
if(!is_opera){
menuobj.style.clip='rect(auto,auto,auto,auto)';
}

setMenuPosition(showid,offset);

if(is_ie&&is_ie<7){
if(!jsmenu['iframe'][layer]){
variframe=document.createElement('iframe');
iframe.style.display='none';
iframe.style.position='absolute';
iframe.style.filter='progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)';
$('append_parent')?$('append_parent').appendChild(iframe):menuobj.parentNode.appendChild(iframe);
jsmenu['iframe'][layer]=iframe;
}
jsmenu['iframe'][layer].style.top=menuobj.style.top;
jsmenu['iframe'][layer].style.left=menuobj.style.left;
jsmenu['iframe'][layer].style.width=menuobj.w;
jsmenu['iframe'][layer].style.height=menuobj.h;
jsmenu['iframe'][layer].style.display='block';
}

if(maxh&&menuobj.scrollHeight>maxh){
menuobj.style.height=maxh+'px';
if(is_opera){
menuobj.style.overflow='auto';
}else{
menuobj.style.overflowY='auto';
}
}

if(!duration){
setTimeout('hideMenu('+layer+')',timeout);
}

jsmenu['active'][layer]=menuobj;
}

functionsetMenuPosition(showid,offset){
varshowobj=$(showid);
varmenuobj=$(showid+'_menu');
if(isUndefined(offset))offset=0;
if(showobj){
showobj.pos=fetchOffset(showobj);
showobj.X=showobj.pos['left'];
showobj.Y=showobj.pos['top'];
showobj.w=showobj.offsetWidth;
showobj.h=showobj.offsetHeight;
menuobj.w=menuobj.offsetWidth;
menuobj.h=menuobj.offsetHeight;
if(offset<3){
menuobj.style.left=(showobj.X+menuobj.w>document.body.clientWidth)&&(showobj.X+showobj.w-menuobj.w>=0)?showobj.X+showobj.w-menuobj.w+'px':showobj.X+'px';
menuobj.style.top=offset==1?showobj.Y+'px':(offset==2||((showobj.Y+showobj.h+menuobj.h>document.documentElement.scrollTop+document.documentElement.clientHeight)&&(showobj.Y-menuobj.h>=0))?(showobj.Y-menuobj.h)+'px':showobj.Y+showobj.h+'px');
}elseif(offset==3){
menuobj.style.left=(document.body.clientWidth-menuobj.clientWidth)/2+document.body.scrollLeft+'px';
menuobj.style.top=(document.body.clientHeight-menuobj.clientHeight)/2+document.body.scrollTop+'px';
}
if(menuobj.style.clip&&!is_opera){
menuobj.style.clip='rect(auto,auto,auto,auto)';
}
}
}

functionhideMenu(layer){
if(isUndefined(layer))layer=0;
if(jsmenu['active'][layer]){
try{
$(jsmenu['active'][layer].ctrlkey).className=ctrlobjclassName;
}catch(e){}
clearTimeout(jsmenu['timer'][jsmenu['active'][layer].ctrlkey]);
jsmenu['active'][layer].style.display='none';
if(is_ie&&is_ie<7&&jsmenu['iframe'][layer]){
jsmenu['iframe'][layer].style.display='none';
}
jsmenu['active'][layer]=null;
}
}

functionfetchOffset(obj){
varleft_offset=obj.offsetLeft;
vartop_offset=obj.offsetTop;
while((obj=obj.offsetParent)!=null){
left_offset+=obj.offsetLeft;
top_offset+=obj.offsetTop;
}
return{'left':left_offset,'top':top_offset};
}

functionebygum(eventobj){
if(!eventobj||is_ie){
window.event.cancelBubble=true;
returnwindow.event;
}else{
if(eventobj.target.type=='submit'){
eventobj.target.form.submit();
}
eventobj.stopPropagation();
returneventobj;
}
}

functionmenuoption_onclick_function(e){
this.clickfunc();
hideMenu();
}

functionmenuoption_onclick_link(e){
choose(e,this);
}

functionmenuoption_onmouseover(e){
this.className='popupmenu_highlight';
}

functionmenuoption_onmouseout(e){
this.className='popupmenu_option';
}

functionchoose(e,obj){
varlinks=obj.getElementsByTagName('a');
if(links[0]){
if(is_ie){
links[0].click();
window.event.cancelBubble=true;
}else{
if(e.shiftKey){
window.open(links[0].href);
e.stopPropagation();
e.preventDefault();
}else{
window.location=links[0].href;
e.stopPropagation();
e.preventDefault();
}
}
hideMenu();
}
}

functionsmiletypescroll(direct){
if(direct==0){
$('smileytypes').scrollTop-=28;
}else{
$('smileytypes').scrollTop+=28;
}
}

varAjaxs=newArray();
varAjaxStacks=newArray(0,0,0,0,0,0,0,0,0,0);
varattackevasive=isUndefined(attackevasive)?0:attackevasive;
functionAjax(recvType,waitId){

for(varstackId=0;stackId<AjaxStacks.length&&AjaxStacks[stackId]!=0;stackId++);
AjaxStacks[stackId]=1;

varaj=newObject();

aj.loading='Loading...';//public
aj.recvType=recvType?recvType:'XML';//public
aj.waitId=waitId?$(waitId):null;//public

aj.resultHandle=null;//private
aj.sendString='';//private
aj.targetUrl='';//private
aj.stackId=0;
aj.stackId=stackId;

aj.setLoading=function(loading){
if(typeofloading!=='undefined'&&loading!==null)aj.loading=loading;
}

aj.setRecvType=function(recvtype){
aj.recvType=recvtype;
}

aj.setWaitId=function(waitid){
aj.waitId=typeofwaitid=='object'?waitid:$(waitid);
}

aj.createXMLHttpRequest=function(){
varrequest=false;
if(window.XMLHttpRequest){
request=newXMLHttpRequest();
if(request.overrideMimeType){
request.overrideMimeType('text/xml');
}
}elseif(window.ActiveXObject){
varversions=['Microsoft.XMLHTTP','MSXML.XMLHTTP','Microsoft.XMLHTTP','Msxml2.XMLHTTP.7.0','Msxml2.XMLHTTP.6.0','Msxml2.XMLHTTP.5.0','Msxml2.XMLHTTP.4.0','MSXML2.XMLHTTP.3.0','MSXML2.XMLHTTP'];
for(vari=0;i<versions.length;i++){
try{
request=newActiveXObject(versions[i]);
if(request){
returnrequest;
}
}catch(e){}
}
}
returnrequest;
}

aj.XMLHttpRequest=aj.createXMLHttpRequest();
aj.showLoading=function(){
if(aj.waitId&&(aj.XMLHttpRequest.readyState!=4||aj.XMLHttpRequest.status!=200)){
changedisplay(aj.waitId,'');
aj.waitId.innerHTML='<span><imgsrc="'+IMGDIR+'/loading.gif">'+aj.loading+'</span>';
}
}

aj.processHandle=function(){
if(aj.XMLHttpRequest.readyState==4&&aj.XMLHttpRequest.status==200){
for(kinAjaxs){
if(Ajaxs[k]==aj.targetUrl){
Ajaxs[k]=null;
}
}
if(aj.waitId)changedisplay(aj.waitId,'none');
if(aj.recvType=='HTML'){
aj.resultHandle(aj.XMLHttpRequest.responseText,aj);
}elseif(aj.recvType=='XML'){
aj.resultHandle(aj.XMLHttpRequest.responseXML.lastChild.firstChild.nodeValue,aj);
}
AjaxStacks[aj.stackId]=0;
}
}

aj.get=function(targetUrl,resultHandle){

setTimeout(function(){aj.showLoading()},500);
if(in_array(targetUrl,Ajaxs)){
returnfalse;
}else{
Ajaxs.push(targetUrl);
}
aj.targetUrl=targetUrl;
aj.XMLHttpRequest.onreadystatechange=aj.processHandle;
aj.resultHandle=resultHandle;
vardelay=attackevasive&1?(aj.stackId+1)*1001:100;
if(window.XMLHttpRequest){
setTimeout(function(){
aj.XMLHttpRequest.open('GET',aj.targetUrl);
aj.XMLHttpRequest.send(null);},delay);
}else{
setTimeout(function(){
aj.XMLHttpRequest.open("GET",targetUrl,true);
aj.XMLHttpRequest.send();},delay);
}

}
aj.post=function(targetUrl,sendString,resultHandle){
setTimeout(function(){aj.showLoading()},500);
if(in_array(targetUrl,Ajaxs)){
returnfalse;
}else{
Ajaxs.push(targetUrl);
}
aj.targetUrl=targetUrl;
aj.sendString=sendString;
aj.XMLHttpRequest.onreadystatechange=aj.processHandle;
aj.resultHandle=resultHandle;
aj.XMLHttpRequest.open('POST',targetUrl);
aj.XMLHttpRequest.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
aj.XMLHttpRequest.send(aj.sendString);
}
returnaj;
}

functionnewfunction(func){
varargs=newArray();
for(vari=1;i<arguments.length;i++)args.push(arguments[i]);
returnfunction(event){
doane(event);
window[func].apply(window,args);
returnfalse;
}
}

functionchangedisplay(obj,display){
if(display=='auto'){
obj.style.display=obj.style.display==''?'none':'';
}else{
obj.style.display=display;
}
returnfalse;
}

varevalscripts=newArray();
functionevalscript(s){
if(s.indexOf('<script')==-1)returns;
varp=/<script[^\>]*?src=\"([^\>]*?)\"[^\>]*?(reload=\"1\")?(?:charset=\"([\w\-]+?)\")?><\/script>/ig;
vararr=newArray();
while(arr=p.exec(s)){
appendscript(arr[1],'',arr[2],arr[3]);
}
s=s.replace(p,'');
p=/<script(.*?)>([^\x00]+?)<\/script>/ig;
while(arr=p.exec(s)){
appendscript('',arr[2],arr[1].indexOf('reload=')!=-1);
}
returns;
}

functionappendscript(src,text,reload,charset){
varid=hash(src+text);
if(!reload&&in_array(id,evalscripts))return;
if(reload&&$(id)){
$(id).parentNode.removeChild($(id));
}

evalscripts.push(id);
varscriptNode=document.createElement("script");
scriptNode.type="text/javascript";
scriptNode.id=id;
scriptNode.charset=charset;
try{
if(src){
scriptNode.src=src;
}elseif(text){
scriptNode.text=text;
}
$('append_parent').appendChild(scriptNode);
}catch(e){}
}

functionstripscript(s){
returns.replace(/<script.*?>.*?<\/script>/ig,'');
}