JavaScript 应用类库代码
JavaScript 应用类库代码
发布时间:2016-12-30 来源:查字典编辑
摘要:/*$获取指定对象@element对象名可以使用对象名集合,返回值为对象的集合如果您使用了Prototype类库,请把该函数注释掉Sams_...

/*$获取指定对象

@element对象名

可以使用对象名集合,返回值为对象的集合

如果您使用了Prototype类库,请把该函数注释掉

Sams_object.Get()中同样实现该函数的所有功能

*/

function$(element){

if(arguments.length>1){

for(vari=0,elements=[],length=arguments.length;i<length;i++)

elements.push($(arguments[i]));

returnelements;

}

if(typeofelement=='string')

element=document.getElementById(element);

returnelement;

}

///浏览器相关操作

varSams_browse={

/*检测浏览信息*/

checkBrowser:function()

{

this.ver=navigator.appVersion

this.dom=document.getElementById?1:0

this.ie6=(this.ver.indexOf("MSIE6")>-1&&this.dom)?1:0;

this.ie5=(this.ver.indexOf("MSIE5")>-1&&this.dom)?1:0;

this.ie4=(document.all&&!this.dom)?1:0;

this.ns5=(this.dom&&parseInt(this.ver)>=5)?1:0;

this.ns4=(document.layers&&!this.dom)?1:0;

this.mac=(this.ver.indexOf('Mac')>-1)?1:0;

this.ope=(navigator.userAgent.indexOf('Opera')>-1);

this.ie=(this.ie6||this.ie5||this.ie4)

this.ns=(this.ns4||this.ns5)

this.bw=(this.ie6||this.ie5||this.ie4||this.ns5||this.ns4||this.mac||this.ope)

this.nbw=(!this.bw)

returnthis;

},

/*设为首页

@url要设为首页的地址

*/

SetDefault:function()

{

this.style.behavior='url(#default#homepage)';

this.setHomePage(this.GetUrl());

returnfalse;

},

/*复制指定URL地址

@Msg要写入剪贴板的字符集

*/

SetCopy:function(Msg){

if(navigator.userAgent.toLowerCase().indexOf('ie')>-1){

clipboardData.setData('Text',Msg);

alert("网址“"+Msg+"”n已经复制到您的剪贴板中n您可以使用Ctrl+V快捷键粘贴到需要的地方");

}

else

{

prompt("请复制网站地址:",Msg);

}

},

/*加入收藏

@site站点名称

@url地址

*/

AddBookmark:function(site,url){

if(navigator.userAgent.toLowerCase().indexOf('ie')>-1){

window.external.addFavorite(url,site)

}elseif(navigator.userAgent.toLowerCase().indexOf('opera')>-1){

alert("请使用Ctrl+T将本页加入收藏夹");

}else{

alert("请使用Ctrl+D将本页加入收藏夹");

}

},

/*打开Url指定宽度和高度的窗口*/

OpenWindows:function(url,width,height)

{

window.open(url,'newwin','width='+width+',height='+height);

returnfalse;

},

/*禁止浏览器的Javascript错误提示*/

CloseError:function(){

window.onerror=function(){returntrue;};

},

/*获取浏览器URL*/

GetUrl:function(){

returnlocation.href;

},

/*获取URL参数*/

GetUrlParam:function(){

returnlocation.search;

},

/*获取页面来源*/

GetFrom:function(){

returndocument.referrer;

},

/*获取指定的URL参数值

@name参数名

*/

Request:function(name){

varGetUrl=this.GetUrl();

varPlist=newArray();

if(GetUrl.indexOf('?')>0)

{

Plist=GetUrl.split('?')[1].split('&');

}

elseif(GetUrl.indexOf('#')>0)

{

Plist=GetUrl.split('#')[1].split('&');

}

if(GetUrl.length>0)

{

for(vari=0;i<Plist.length;i++)

{

varGetValue=Plist[i].split('=');

if(GetValue[0].toUpperCase()==name.toUpperCase())

{

returnGetValue[1];

break;

}

}

return;

}

},

/*直接将HTML写到新窗口

@title标题

@msg内容

*/

Popmsg:functionPopIt(title,msg)

{

varpopup=window.open('','popDialog','height=500,width=400,scrollbars=yes');

popup.document.write('<html><title>'+title+'</title><style>body{margin:10px;font:13pxArial;}span{text-line:20px;}</style><body><spanstyle='font:14pxarial;'>'+msg+'</span></body></html>');

popup.document.close();

}

};

///对象操作

varSams_object={

/*创建一个DIV对象

@ID要创建的对象ID

@ClassName创建对象的Class

@SetValue设置该对象值

@ToDiv将对象追加到指定的对象,如指定的对象不存在,则追加在Body的后面

返回创建后的对象

*/

CreateDiv:function(ID,ClassName,SetValue,ToDiv){

varcreatediv=document.createElement('div');

if(ID!=null)creatediv.id=ID;

creatediv.style.position='absolute';

if(ClassName!=null)creatediv.className=ClassName;

if(this.Get(ToDiv))

{

this.Get(ToDiv).appendChild(creatediv);

}

else

{

document.getElementsByTagName('body')[0].appendChild(creatediv);

}

this.SetValue(ID,SetValue);

returnthis.Get(ID);

},

/*删除指定DIV对象

@objid要删除的对象ID

返回Bool操作结果

*/

DeleteDiv:function(objid)

{

try

{

if(this.Get(objid))

{

varGetParent=this.Get(objid).parentNode;

GetParent.removeChild(this.Get(objid));

returntrue;

}

else

{

returnfalse;

}

}

catch(e)

{

returnfalse;

}

},

/*获取浏览器对象

@id要获取的对象ID

可以使用对象名集合,返回值为对象的集合

*/

Get:function(objid){

if(arguments.length>1){

for(vari=0,objids=[],length=arguments.length;i<length;i++)

objids.push(this.Get(arguments[i]));

returnobjids;

}

if(typeofobjid=='string')

{

if(document.getElementById){

objid=document.getElementById(objid);

}elseif(document.all){

objid=document.all[objid];

}elseif(document.layers){

objid=document.layers[objid];

}

}

returnobjid;

},

/*获取对象的值

@objid对象ID

*/

GetValue:function(objid){

if(typeofobjid=='string')

{

vargetTagName=this.Get(objid).tagName.toLowerCase();

if(getTagName=='input'||getTagName=='textarea'||getTagName=='select')

{

returnthis.Get(objid).value;

}

elseif(getTagName=='div'||getTagName=='span')

{

returnthis.Get(objid).innerText;

}

}

elseif(typeofobjid=='object')

{

returnobjid.value;

}

},

/*设置指定对象的值,实现可以直接赋值或清除操作

@objid对象ID

@inserValue传入值(可选项Null:清除该ID的值,则直接赋值)

*/

SetValue:function(objid,inserValue){

vargetTagName=this.Get(objid).tagName.toLowerCase();

if(inserValue==null)inserValue='';

if(getTagName=='input'||getTagName=='textarea')

{

this.Get(objid).value=inserValue;

}

elseif(getTagName=='div'||getTagName=='sapn')

{

this.Get(objid).innerText=inserValue;

}

},

/*拷贝对象值到剪贴板

@str对象值

*/

CopyCode:function(str){

varrng=document.body.createTextRange();

rng.moveToElementText(str);

rng.scrollIntoView();

rng.select();

rng.execCommand("Copy");

rng.collapse(false);

},

/*显示隐藏一个对象

@Objid对象ID

@isshow具体操作,指定Obj为False:none或者True:block(可选)

*/

ShowHidd:function(objid,isshow){

if(isshow!=null)

{

if(isshow)

{

this.Get(objid).style.display='block';

}

else

{

this.Get(objid).style.display='none';

}

}

else

{

if(this.Get(objid).style.display=='none')

{

this.Get(objid).style.display='block';

}

else

{

this.Get(objid).style.display='none';

}

}

},

/*当前对象是否可见

@objid对象ID

*/

IsVisible:function(objid){

if(this.Get(objid))

{

try

{

if(this.Get(objid).style.display=='none')

{

returnfalse

}

if(this.Get(objid).style.visibility=='hidden')

{

returnfalse;

}

returntrue;

}

catch(e)

{

returnfalse;

}

}

else

{

returnfalse;

}

}

};

///字符处理

varSams_string={

/*取左边的指定长度的值

@str要处理的字符集

@n长度

*/

Left:function(str,n)

{

if(str.length>0)

{

if(n>str.length)n=str.length;

returnstr.substr(0,n)

}

else

{

return;

}

},

/*取右边的指定长度的值

@str要处理的字符集

@n长度

*/

Right:function(str,n)

{

if(str.length>0)

{

if(n>=str.length)returnstr;

returnstr.substr(str.length-n,n);

}

else

{

return;

}

},

/*Trim:清除两边空格

@str要处理的字符集

*/

Trim:function(str)

{

if(typeofstr=='string')returnstr.replace(/(^s*)|(s*$)/g,'');

},

/*LTrim:清除左边的空格

@str要处理的字符集

*/

Ltrim:function(str)

{

if(typeofstr=='string')returnstr.replace(/(^s*)/g,'');

},

/*RTrim:清除右边的空格

@str要处理的字符集

*/

Rtrim:function(str)

{

if(typeofstr=='string')returnstr.replace(/(s*$)/g,'');

},

/*清除前后的非字符

@str要处理的字符集

*/

strip:function(str){

if(typeofstr=='string')returnstr.replace(/^s+/,'').replace(/(^s*)|(s*$)/g,'');

},

/*过滤字符里面的HTML标签

@str要处理的字符集

*/

stripTags:function(str){

if(typeofstr=='string')returnstr.replace(/</?[^>]+>/gi,'').replace(/(^s*)|(s*$)/g,'');

}

};

///时间相关操作

varSams_time={

/*获取当天日期yyyy-MM-dd*/

GetDateNow:function(){

vard,y,m,dd;

d=newDate();

y=d.getYear();

m=d.getMonth()+1;

dd=d.getDate();

returny+"-"+m+"-"+dd;

},

/*获取指定日期后的特定天数的日期值

@toDate当前指定的日期

@N要添加的日期数

*/

AddDays:function(toDate,N){

varaDate=this._cvtISOToDate(toDate);

if(!aDate)return"";

varmillis=86400000*N;

aDate=newDate(aDate.getTime()+millis);

returnthis._fmtDateISO(aDate);

},

_fmtDateISO:function(aDate){

with(aDate){

varmm=getMonth()+1;

if(mm<10){mm='0'+mm;}

vardd=getDate();

if(dd<10){dd='0'+dd;}

return(getFullYear()+'-'+mm+'-'+dd);

}

},

_cvtISOToDate:function(isoDate){

varatomDate=isoDate.split('-');

varaDate=newDate(parseInt(atomDate[0],10),parseInt(atomDate[1],10)-1,parseInt(atomDate[2],10),6,0,0);

returnaDate;

}

};

///图像相关操作

varSams_media={

/*为单一图像添加鼠标中键放大缩小功能,批量可以直接用ResizeImage(指定添加该功能的图片大小:Int)即可(该功能只适用于IE)

objid对象ID

*/

ZoomFun:function(objid){

Sams_object.Get(objid).onmousewheel=function(){returnSams_media.imagecontrol(this);}

},

/*重置图片尺寸同时添加放大功能(该功能只适用于IE)

@IntSize指定图像的大小

如果适合图像大小就添加放大缩小功能

*/

ResizeImage:function(IntSize){

varimgsinlog=document.getElementsByTagName('img');

for(j=0;j<imgsinlog.length;j++){

if(imgsinlog[j].width>=IntSize){

imgsinlog[j].width=IntSize;

imgsinlog[j].style.cursor='pointer';

imgsinlog[j].onclick=function(){window.open(this.src);}

if(navigator.userAgent.toLowerCase().indexOf('ie')>-1){

imgsinlog[j].title='您可以用鼠标中键或者使用Ctrl+鼠标滚轮缩放图片,点击图片可在新窗口打开';

imgsinlog[j].onmousewheel=function(){returnSams_media.imagecontrol(this);};

}

else

{

imgsinlog[j].title='点击图片可在新窗口打开';

}

}

}

},

imagecontrol:function(obj){

varzoom=parseInt(obj.style.zoom,10)||100;zoom+=event.wheelDelta/12;

if(zoom>0)obj.style.zoom=zoom+'%';

returnfalse;

},

/*如果图像出现下载不了等异常,显示的错误提示图片

@errimgpath显示错误提示的图像路径

*/

ImagesError:function(errimgpath){

varimglist=document.getElementsByTagName('img');

for(j=0;j<imglist.length;j++){

imglist[j].onerror=function(){

this.src=errimgpath;

}

}

},

/*显示媒体

@mFile文件路径

@mFileType文件类型(可为空,如为Flash,要指定为swf类型)

@ObjID对象ID

@mWidth显示的对象宽度

@mHeight显示对象的高度

注:可以指定对象的ID,如果ID不存在,会自动创建,追加在Body后面

*/

ShowMedia:function(mFile,mFileType,ObjID,mWidth,mHeight){

varmediaStr;

switch(mFileType){

case"swf":

mediaStr="<objectcodeBase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0'classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'width='"+mWidth+"'height='"+mHeight+"'><paramname='movie'value='"+mFile+"'><paramname='quality'value='high'><paramname='AllowScriptAccess'value='never'><embedsrc='"+mFile+"'quality='high'pluginspage='http://www.macromedia.com/go/getflashplayer'type='application/x-shockwave-flash'width='"+mWidth+"'height='"+mHeight+"'></embed></OBJECT>";

break;

default:

mediaStr="<objectwidth='"+mWidth+"'height='"+mHeight+"'classid='CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6'><paramname='url'value='"+mFile+"'/><embedwidth='"+mWidth+"'height='"+mHeight+"'type='application/x-mplayer2'src='"+mFile+"'></embed></object>";

}

varmediaDiv=Sams_object.Get(ObjID);

if(mediaDiv){

mediaDiv.innerHTML=mediaStr;

}

else

{

mediaDiv=document.createElement("div");

mediaDiv.id=ObjID;

mediaDiv.innerHTML=mediaStr;

document.getElementsByTagName('body')[0].appendChild(mediaDiv);

}

returnfalse;

}

};

///样式相关操作

varSams_style={

/*改变字体大小

@objid对象ID

@size字号

*/

doZoom:function(objid,size){

Sams_object.Get(objid).style.fontSize=size+'px';

},

/*改变指定对象样式

@objid对象ID

@className要更改的ClassName

*/

ClassName:function(objid,className){

Sams_object.Get(objid).className=className;

},

/*对象定位

@obj要定位的对象

返回X.Y结果的数组对象

*/

GotoXY:function(obj){

vart=obj.offsetTop;

varl=obj.offsetLeft;

while(obj=obj.offsetParent){

t+=obj.offsetTop;

l+=obj.offsetLeft;

}

returnArray(t,l);

}

};

///科学计算

varSams_account={

/*逢1进10计算

@数值

*/

GetTen:function(i)

{

varitems_One,Get_One;

if(i.length>1&&(/^d+$/.test(i)))

{

items_One=i.substr(0,i.length-1);

Get_One=i.substr(i.length-1,1);

if(parseInt(Get_One)>0)

{

items_One=parseInt(items_One)+1;

items_One=items_One+'0';

}

else

{

items_One=items_One+'0';

}

}

else

{

items_One=i;

}

returnitems_One;

}

};

///数据验证(所有数值返回值均为Bool型)

varSams_validate={

/*是否是数字型数据

@str字符集

*/

IsNumber:function(str){

if(/^d+$/.test(str)){returntrue;}else{returnfalse;}

},

/*是否是数字型数据

@objid对象ID

*/

IsNumberObj:function(objid){

returnthis.IsNumber(Sams_object.GetValue(objid));

},

/*是否是自然数型数据

@str字符集

*/

IsInt:function(str){

if(/^(+|-)?d+$/.test(str)){returntrue;}else{returnfalse;}

},

/*是否是自然数型数据

@objid对象ID

*/

IsIntObj:function(objid){

returnthis.IsInt(Sams_object.GetValue(objid));

},

/*是否是中文字符

@str字符集

*/

IsChinese:function(str)

{

if(/^[u4e00-u9fa5]+$/.test(str)){returntrue;}else{returnfalse;}

},

/*是否是中文字符

@objid对象ID

*/

IsChineseObj:function(objid)

{

returnthis.IsChinese(Sams_object.GetValue(objid));

},

/*是否为英文字母

@str字符集

*/

IsLower:function(str)

{

if(/^[A-Za-z]+$/.test(str)){returntrue}else{returnfalse;}

},

/*是否为英文字母

@objid对象ID

*/

IsLowerObj:function(objid)

{

returnthis.IsLower(Sams_object.GetValue(objid));

},

/*是否为正确的网址

@str字符集

*/

IsUrl:function(str)

{

varmyReg=/^((http:[/][/])?w+([.]w+|[/]w*)*)?$/;

if(myReg.test(str)){returntrue;}else{returnfalse;}

},

/*是否为正确的网址

@objid对象ID

*/

IsUrlObj:function(objid)

{

returnthis.IsUrl(Sams_object.GetValue(objid));

},

/*是否为正确的Email形式

@str字符集

*/

IsEmail:function(str)

{

varmyReg=/^([-_A-Za-z0-9.]+)@([_A-Za-z0-9]+.)+[A-Za-z0-9]{2,3}$/;

if(myReg.test(str)){returntrue;}else{returnfalse;}

},

/*是否为正确的Email形式

@objid对象ID

*/

IsEmailObj:function(objid)

{

returnthis.IsEmail(Sams_object.GetValue(objid));

},

/*是否为正确的手机号码

@str字符集

*/

IsMobile:function(str)

{

varregu=/(^[1][3][0-9]{9}$)|(^0[1][3][0-9]{9}$)/;

varre=newRegExp(regu);

if(re.test(str)){returntrue;}else{returnfalse;}

},

/*是否为正确的手机号码

@objid对象ID

*/

IsMobileObj:function(objid)

{

returnthis.IsMobile(Sams_object.GetValue(objid));

}

};

/*

实现Ajax功能

Sams_ajax.SendRequest('GET',url,null,recall,"addtohome");

Sams_ajax.SendRequest('GET',url,null,null);

obj.responseText;

*/

varSams_ajax={

_objPool:[],

_getInstance:function(){

for(vari=0;i<this._objPool.length;i++){

if(this._objPool[i].readyState==0||this._objPool[i].readyState==4){

returnthis._objPool[i];

}

}

this._objPool[this._objPool.length]=this._createObj();

returnthis._objPool[this._objPool.length-1];

},

_createObj:function(){

if(window.XMLHttpRequest){

varobjXMLHttp=newXMLHttpRequest();

}

else{

varMSXML=['MSXML2.XMLHTTP.5.0','MSXML2.XMLHTTP.4.0','MSXML2.XMLHTTP.3.0','MSXML2.XMLHTTP','Microsoft.XMLHTTP'];

for(varn=0;n<MSXML.length;n++){

try{

varobjXMLHttp=newActiveXObject(MSXML[n]);

break;

}

catch(e){

}

}

}

if(objXMLHttp.readyState==null){

objXMLHttp.readyState=0;

objXMLHttp.addEventListener("load",function(){

objXMLHttp.readyState=4;

if(typeofobjXMLHttp.onreadystatechange=="function"){

objXMLHttp.onreadystatechange();

}

},false);

}

returnobjXMLHttp;

},

///开始发送请求

SendRequest:function(method,url,data,callback,funparam,funparam2){

varobjXMLHttp=this._getInstance();

with(objXMLHttp){

try{

if(url.indexOf("?")>0){

url+="&randnum="+Math.random();

}

else{

url+="?randnum="+Math.random();

}

open(method,url,true);

setRequestHeader('Content-Type','application/x-www-form-urlencoded;charset=UTF-8');

send(data);

onreadystatechange=function(){

if(objXMLHttp.readyState==4&&(objXMLHttp.status==200||objXMLHttp.status==304))

{

callback(objXMLHttp,funparam,funparam2);

}else{

callback(null,funparam,funparam2);

}

}

}

catch(e){

alert(e);

}

}

}

};

///Cookies操作

varSams_cookies={

/*cookies设置函数

@nameCookies名称

@value值

*/

setCookie:function(name,value)

{

try

{

varargv=setCookie.arguments;

varargc=setCookie.arguments.length;

varexpires=(argc>2)?argv[2]:null;

if(expires!=null)

{

varLargeExpDate=newDate();

LargeExpDate.setTime(LargeExpDate.getTime()+(expires*1000*3600*24));

}

document.cookie=name+"="+escape(value)+((expires==null)?"":(";expires="+LargeExpDate.toGMTString()));

returntrue;

}

catch(e)

{

returnfalse;

}

},

/*cookies读取函数

@NameCookies名称

返回值Cookies值

*/

getCookie:function(Name)

{

varsearch=Name+"="

if(document.cookie.length>0)

{

offset=document.cookie.indexOf(search)

if(offset!=-1)

{

offset+=search.length

end=document.cookie.indexOf(";",offset)

if(end==-1)end=document.cookie.length

returnunescape(document.cookie.substring(offset,end))

}

else

{

return;

}

}

}

};

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新Javascript教程学习
热门Javascript教程学习
编程开发子分类