函數就是包裹在花括號中的代碼塊,前面使用了關鍵詞 function:
function functionname()
{
這裡是要執行的代碼
}
當調用該函數時,會執行函數內的代碼。
可以在某事件發生時直接調用函數(比如當用戶點擊按鈕時),並且可由 JavaScript 在任何位置進行調用。
提示:JavaScript 對大小寫敏感。關鍵詞 function 必須是小寫的,並且必須以與函數名稱相同的大小寫來調用函數。
字符串長度截取
functiocutstr(strlen{
vatemp,
icoun,
patr/[^\x-\xff]/,
strr"";
fo(vastr.lengthi++{
i(icounle{
temstr.substr(i);
i(patrn.exec(temp=null{
icounicoun
els{
icounicoun
}
strr+temp
els{
break;
}
}
returstrr"..."
}
替換全部
String.prototype.replaceAlfunction(ss{
returthis.replace(neRegExp(s"gm")s)
}
清除空格
String.prototype.trifunction({
vareExtraSpac/^\s*(.*?)\s+$/;
returthis.replace(reExtraSpace"$")
}
清除左空格/右空格
functioltrim(s)returs.replace/^(\s*| *)/"")} functiortrim(s)returs.replace/(\s*| *)$/"")}
判斷是否以某個字符串開頭
String.prototype.startWitfunctio(s{
returthis.indexOf(s=
}
判斷是否以某個字符串結束
String.prototype.endWitfunctio(s{
vathis.lengts.length;
retur(>&this.lastIndexOf(s=d)
}
轉義html標簽
functioHtmlEncode(text{
returtext.replace(/&/g'&').replace(/\"/g'"').replace(/</g'<').replace(/>/g'>')
}
時間日期格式轉換
Date.prototype.Formafunction(formatStr{
vastformatStr;
vaWee['日''一''二''三''四''五''六'];
ststr.replace(/yyyy|YYYY/this.getFullYear());
ststr.replace(/yy|YY/(this.getYear((this.getYear().toString('(this.getYear());
ststr.replace(/MM/(this.getMonth((this.getMonth().toString('(this.getMonth());
ststr.replace(/M/g(this.getMonth());
ststr.replace(/w|W/gWeek[this.getDay()]);
ststr.replace(/dd|DD/this.getDate(this.getDate().toString('this.getDate());
ststr.replace(/d|D/gthis.getDate());
ststr.replace(/hh|HH/this.getHours(this.getHours().toString('this.getHours());
ststr.replace(/h|H/gthis.getHours());
ststr.replace(/mm/this.getMinutes(this.getMinutes().toString('this.getMinutes());
ststr.replace(/m/gthis.getMinutes());
ststr.replace(/ss|SS/this.getSeconds(this.getSeconds().toString('this.getSeconds());
ststr.replace(/s|S/gthis.getSeconds());
returstr
}
判斷是否為數字類型
functioisDigit(value{
vapatr/^[-]*$/;
i(patrn.exec(value=nul|valu=""{
returfalse
els{
returtrue
}
}
設置cookie值
functiosetCookie(namevalueHours{
vaneDate();
vaoffse;
vautd.getTime((d.getTimezoneOffset();
vanut(offset);
vaexneDate(nd);
exp.setTime(exp.getTime(Hour);
document.cookinam"=escape(value";path=/;expires=exp.toGMTString(";domain=doc.com;"
}
獲取cookie值
functiogetCookie(name{
vaardocument.cookie.match(neRegExp("(^)nam"=([^;]*)(;|$)"));
i(ar!nullreturunescape(arr[]);
returnull
}
加入收藏夾
functioAddFavorite(sURLsTitle{
tr{
window.external.addFavorite(sURLsTitle)
catch(e{
tr{
window.sidebar.addPanel(sTitlesURL"")
catch(e{
alert("加入收藏失敗,請使用Ctrl+D進行添加")
}
}
}
設為首頁
functiosetHomepage({
i(document.all{
document.body.style.behavio'url(#default#homepage)';
document.body.setHomePage('http://wcboy.com')
elsi(window.sidebar{
i(window.netscape{
tr{
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect")
catch(e{
alert("該操作被浏覽器拒絕,如果想啟用該功能,請在地址欄內輸about:config,然後將signed.applets.codebase_principal_suppor值該為true")
}
}
vaprefComponents.classes['@mozilla.org/preferences-service;'].getService(Components.interfaces.nsIPrefBranch);
prefs.setCharPref('browser.startup.homepage''http://wcboy.com')
}
}
加載樣式文件
functioLoadStyle(url{
tr{
document.createStyleSheet(url)
catch(e{
vacssLindocument.createElement('link');
cssLink.re'stylesheet';
cssLink.typ'text/css';
cssLink.hreurl;
vaheadocument.getElementsByTagName('head')[];
head.appendChild(cssLink)
}
}
返回腳本內容
functioevalscript(s{
if(s.indexOf('<script'=-returs;
va/<script[^\>]*?>([^\x]*?)<\/script>/ig;
vaar[];
while(arp.exec(s){
vap/<script[^\>]*?src=\"([^\>]*?)\"[^\>]*?(reload=\"\")?(?:charset=\"([\w\-]+?)\")?><\/script>/i;
vaarr[];
arrp.exec(arr[]);
if(arr{
appendscript(arr[]''arr[]arr[]);
els{
p/<script(.*?)>([^\x]+?)<\/script>/i;
arrp.exec(arr[]);
appendscript(''arr[]arr[].indexOf('reload='!-);
}
}
returs;
}
清除腳本內容
functiostripscript(s{
returs.replace(/<script.*?>.*?<\/script>/ig'');
}
動態加載腳本文件
functioappendscript(srctextreloadcharset{
vaihash(srtext);
if(!reloa&in_array(idevalscripts)return;
if(reloa&$(id){
$(id).parentNode.removeChild($(id));
}
evalscripts.push(id);
vascriptNoddocument.createElement("script");
scriptNode.typ"text/javascript";
scriptNode.iid;
scriptNode.charsecharsecharse(BROWSER.firefodocument.characterSedocument.charset);
tr{
if(src{
scriptNode.srsrc;
scriptNode.onloadDonfalse;
scriptNode.onloafunctio({
scriptNode.onloadDontrue;
JSLOADED[src;
};
scriptNode.onreadystatechangfunctio({
if((scriptNode.readyStat='loaded|scriptNode.readyStat='complete'&!scriptNode.onloadDone{
scriptNode.onloadDontrue;
JSLOADED[src;
}
};
elsif(text){
scriptNode.textext;
}
document.getElementsByTagName('head')[].appendChild(scriptNode);
catch(e{}
}
返回按ID檢索的元素對象
functio$(id{
retur!inuldocument.getElementById(id);
}
跨浏覽器綁定事件
functioaddEventSamp(obj,evt,fn){
if(!oTarget){return;}
i(obj.addEventListener{
obj.addEventListener(evtfnfalse);
}elsif(obj.attachEvent){
obj.attachEvent('on'+evt,fn);
}else{
oTarget["onsEvtTypefn;
}
}
跨浏覽器刪除事件
functiodelEvt(obj,evt,fn){
if(!obj){return;}
if(obj.addEventListener){
obj.addEventListener(evt,fn,false);
}elsif(oTarget.attachEvent){
obj.attachEvent("onevt,fn);
}else{
obj["onevtfn;
}
}
為元素添加on方法
Element.prototype.oElement.prototype.addEventListener;
NodeList.prototype.ofunctio(eventfn{、
[]['forEach'].call(thisfunctio(el{
el.on(eventfn);
});
returthis;
};
為元素添加trigger方法
Element.prototype.triggefunctio(typedata{
vaevendocument.createEvent('HTMLEvents');
event.initEvent(typetruetrue);
event.datdat|{};
event.eventNamtype;
event.targethis;
this.dispatchEvent(event);
returthis;
};
NodeList.prototype.triggefunctio(event{
[]['forEach'].call(thisfunctio(el{
el['trigger'](event);
});
returthis;
};
檢驗URL鏈接是否有效
functiogetUrlState(URL){
vaxmlhttneActiveXObject("microsoft.xmlhttp");
xmlhttp.Open("GET",URLfalse);
try{
xmlhttp.Send();
}catch(e){
}finally{
varesulxmlhttp.responseText;
if(result){
if(xmlhttp.Status==){
return(true);
}else{
return(false);
}
}else{
return(false);
}
}
}
格式化CSS樣式代碼
.functioformatCss(s){//格式化代碼
s.replace(/\s*([\{\}\:\;\,])\s*/g"$");
s.replace(/;\s*;/g";")//清除連續分號
s.replace(/\,[\s\.\#\d]*{/g"{");
s.replace(/([^\s])\{([^\s])/g"${\n\t$");
s.replace(/([^\s])\}([^\n]*)/g"$\n}\n$");
s.replace(/([^\s]);([^\s\}])/g"$;\n\t$");
returs;
}
壓縮CSS樣式代碼
functiocompressCs(s{//壓縮代碼
s.replace(/\/\*(.|\n)*?\*\//g"")//刪除注釋
s.replace(/\s*([\{\}\:\;\,])\s*/g"$");
s.replace(/\,[\s\.\#\d]*\{/g"{")//容錯處理
s.replace(/;\s*;/g";")//清除連續分號
s.match(/^\s*(\S+(\s+\S+)*)\s*$/)//去掉首尾空白
retur(=null"s[];
}
獲取當前路徑
vacurrentPageUr"";
i(typeothis.hre=="undefined"{
currentPageUrdocument.location.toString().toLowerCase();
}els{
currentPageUrthis.href.toString().toLowerCase();
}
判斷是否移動設備
functioisMobile(){
i(typeothis._isMobil=='boolean'){
returthis._isMobile;
}
vascreenWidtthis.getScreenWidth();
vafixViewPortsExperimenrendererModel.runningExperiments.FixViewpor||rendererModel.runningExperiments.fixviewport;
vafixViewPortsExperimentRunninfixViewPortsExperimen&(fixViewPortsExperiment.toLowerCase(=="new");
if(!fixViewPortsExperiment){
if(!this.isAppleMobileDevice()){
screenWidtscreenWidth/window.devicePixelRatio;
}
}
vaisMobileScreenSizscreenWidt;
vaisMobileUserAgenfalse;
this._isMobilisMobileScreenSiz&this.isTouchScreen();
returthis._isMobile;
}
判斷是否移動設備訪問
functioisMobileUserAgent(){
retur(/iphone|ipod|android.*mobile|windows.*phone|blackberry.*mobile/i.test(window.navigator.userAgent.toLowerCase()));
}
判斷是否蘋果移動設備訪問
functioisAppleMobileDevice(){
retur(/iphone|ipod|ipad|Macintosh/i.test(navigator.userAgent.toLowerCase()));
}
判斷是否安卓移動設備訪問
functioisAndroidMobileDevice(){
retur(/android/i.test(navigator.userAgent.toLowerCase()));
}
判斷是否Touch屏幕
functioisTouchScreen(){
retur(('ontouchstartiwindow|window.DocumentTouc&documeninstanceoDocumentTouch);
}
判斷是否打開視窗
functioisViewportOpen({
retur!!document.getElementById('wixMobileViewport');
}
獲取移動設備初始化大小
functiogetInitZoom(){
if(!this._initZoom){
vascreenWidtMath.min(screen.heightscreen.width);
if(this.isAndroidMobileDevice(&!this.isNewChromeOnAndroid()){
screenWidtscreenWidth/window.devicePixelRatio;
}
this._initZooscreenWidt/document.body.offsetWidth;
}
returthis._initZoom;
}
獲取移動設備最大化大小
functiogetZoom(){
vascreenWidt(Math.abs(window.orientation==Math.max(screen.heightscreen.widthMath.min(screen.heightscreen.width);
if(this.isAndroidMobileDevice(&!this.isNewChromeOnAndroid()){
screenWidtscreenWidth/window.devicePixelRatio;
}
vaFixViewPortsExperimenrendererModel.runningExperiments.FixViewpor|rendererModel.runningExperiments.fixviewport;
vaFixViewPortsExperimentRunninFixViewPortsExperimen&(FixViewPortsExperimen=="New|FixViewPortsExperimen=="new");
if(FixViewPortsExperimentRunning){
returscreenWidtwindow.innerWidth;
}else{
returscreenWidtdocument.body.offsetWidth;
}
}
獲取移動設備屏幕寬度
functiogetScreenWidth(){
vasmallerSidMath.min(screen.widthscreen.height);
vafixViewPortsExperimenrendererModel.runningExperiments.FixViewpor|rendererModel.runningExperiments.fixviewport;
vafixViewPortsExperimentRunninfixViewPortsExperimen&(fixViewPortsExperiment.toLowerCase(=="new");
if(fixViewPortsExperiment){
if(this.isAndroidMobileDevice(&!this.isNewChromeOnAndroid()){
smallerSidsmallerSide/window.devicePixelRatio;
}
}
retursmallerSide;
}
完美判斷是否為網址
functioIsURL(strUrl{
varegula/^\b(((https?|ftp):\/\/)?[-a-z-]+(\.[-a-z-]+)*\.(?:com|edu|gov|int|mil|net|org|biz|info|name|museum|asia|coop|aero|[a-z][a-z]|(([-])|([-]\d)|(\d\d)|([-]\d)|\d))\b(\/[-a-z-_:\@&?=+,.!\/~%\$]*)?)$/i
i(regular.test(strUrl){
returtrue;
}els{
returfalse;
}
}
getElementsByClassName
.functiogetElementsByClassName(name{
vatagdocument.getElementsByTagName('*'|document.all;
vael[];
fo(vatags.lengthi++{
i(tags.className{
vactags.className.split(');
fo(vacs.lengthj++{
i(nam=cs[j]{
els.push(tags);
break
}
}
}
}
returels
}
獲取頁面高度
functiogetPageHeight(){
vadocumentg.bodyg.documentElementg.compatMod="BackCompat"
a
g.documentElement;
returMath.max(f.scrollHeighta.scrollHeightd.clientHeight);
}
獲取頁面scrollLeft
functiogetPageScrollLeft(){
vadocument;
retura.documentElement.scrollLef|a.body.scrollLeft;
}
獲取頁面可視寬度
functiogetPageViewWidth(){
vadocumentd.compatMod="BackCompat"
d.body
d.documentElement;
retura.clientWidth;
}
獲取頁面寬度
functiogetPageWidth(){
vadocumentg.bodyg.documentElementg.compatMod="BackCompat"
a
g.documentElement;
returMath.max(f.scrollWidtha.scrollWidthd.clientWidth);
}
獲取頁面scrollTop
functiogetPageScrollTop(){
vadocument;
retura.documentElement.scrollTo|a.body.scrollTop;
}
獲取頁面可視高度
functiogetPageViewHeight({
vadocumentd.compatMod="BackCompat"
d.body
d.documentElement;
retura.clientHeight;
}
去掉url前綴
functioremoveUrlPrefix(a){
a=a.replace(/:/g,":").replace(/./g,".").replace(///g,"/");
while(trim(a).toLowerCase().indexOf("http://")==){
a=trim(a.replace(/http:\/\//i,""));
}
retura;
}
隨機數時間戳
functiouniqueId(){
vaa=Math.random,b=parseInt;
returNumber(neDate()).toString()+b(*a())+b(*a())+b(*a());
}
全角半角轉換
//iCase全到半,半到全,其他不轉化
functiochgCase(sStr,iCase){
if(typeosSt!"string|sStr.lengt<|!(iCas==|iCas=)){
retursStr;
}
vai,oRs=[],iCode;
if(iCase){/*半->全*/
for(i=i<sStr.length;i+=){
iCodsStr.charCodeAt(i);
if(iCod=){
iCod;
}elsif(iCod){
iCod+;
}
oRs.push(String.fromCharCode(iCode));
}
}else{/*全->半*/
for(i=i<sStr.length;i+=){
iCodsStr.charCodeAt(i);
if(iCod=){
iCod;
}elsif(iCod&iCod){
iCod-;
}
oRs.push(String.fromCharCode(iCode));
}
}
returoRs.join("");
}
確認是否鍵盤有效輸入值
functiocheckKey(iKey){
if(iKe=|iKe=){returtrue;}/*空格和異常*/
if(iKey>&iKe){returtrue;}/*數字*/
if(iKey>&iKe){returtrue;}/*字母*/
if(iKey>&iKe){returtrue;}/*數字鍵盤*/
if(iKey>&iKe){returtrue;}/*數字鍵盤*/
if(iKey>&iKe){returtrue;}/*符號*/
if(iKey>&iKe){returtrue;}/*符號*/
returfalse;
}
獲取網頁被卷去的位置
functiogetScrollXY({
returdocument.body.scrollTo{
xdocument.body.scrollLeft,
ydocument.body.scrollTop
}{
xdocument.documentElement.scrollLeft,
ydocument.documentElement.scrollTop
}
}
日期格式化函數+調用方法
Date.prototype.formafunction(format){
va{
"M+this.getMonth()+//month
"d+this.getDate()//day
"h+this.getHours()//hour
"m+this.getMinutes()//minute
"s+this.getSeconds()//second
"q+Math.floor((this.getMonth()+)/)//quarter
"Sthis.getMilliseconds(//millisecond
};
if(/(y+)/.test(format)format=format.replace(RegExp.$,
(this.getFullYear()+"").substr(RegExp.$.length));
for(vaio){
if(neRegExp("("+")").test(format))
formaformat.replace(RegExp.$,RegExp.$.length==o[k:(""o[k]).substr((""o[k]).length));
}
returformat;
}
alert(neDate().format("yyyy-MM-dhh:mm:ss"));
時間個性化輸出功能
./*
.、s顯示為“剛剛”
.、>mi&min顯示與當前時間差“XX分鐘前”
.、>mi&day顯示與當前時間差“今XX:XX”
.、>da&year顯示日期“XX月XXXX:XX”
.、>year顯示具體日期“XXXX年XX月XXXX:XX”
.*/
.functiotimeFormat(time){
vadatneDate(time),
curDatneDate(),
yeadate.getFullYear(),
montdate.getMonth(,
dadate.getDate(),
houdate.getHours(),
minutdate.getMinutes(),
curYeacurDate.getFullYear(),
curHoucurDate.getHours(),
timeStr;
if(yeacurYear){
timeStyea+'年'mont+'月'da+''hou+':'minute;
}else{
vapastTimcurDatdate,
pastpastTime/;
if(pastcurHour){
timeStmont+'月'da+''hou+':'minute;
}elsif(past>){
timeSt'今hou+':'minut+'分';
}else{
vapastcurDate.getMinutes(minute;
if(past){
timeStpast+'分鐘前';
}else{
timeSt'剛剛';
}
}
}
returtimeStr;
}
解決offsetX兼容性問題
./針對火狐不支持offsetX/Y
.functiogetOffset(e){
vatargee.target/當前觸發的目標對象
eventCoord,
pageCoord,
offsetCoord;
/計算當前觸發元素到文檔的距離
pageCoorgetPageCoord(target);
/計算光標到文檔的距離
eventCoor{
window.pageXOffsee.clientX,
window.pageYOffsee.clientY
};
/相減獲取光標到第一個定位的父元素的坐標
offsetCoor{
eventCoord.pageCoord.X,
eventCoord.pageCoord.Y
};
returoffsetCoord;
.}
.functiogetPageCoord(element){
vacoor};
/計算從當前觸發元素到根節點為止,
/各offsetParen元素offsetLefoffsetTo值之和
whil(element){
coord.+element.offsetLeft;
coord.+element.offsetTop;
elemenelement.offsetParent;
}
returcoord;
.}
常用的正則表達式
.//正整數
./^[-]*[-][-]*$/;
.//負整數
./^-[-]*[-][-]*$/;
.//正浮點數
./^(([-]+\.[-]*[-][-]*)|([-]*[-][-]*\.[-]+)|([-]*[-][-]*))$/;
.//負浮點數
./^(-(([-]+\.[-]*[-][-]*)|([-]*[-][-]*\.[-]+)|([-]*[-][-]*)))$/;
.//浮點數
./^(-?\d+)(\.\d+)?$/;
.//email地址
./^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
.//url地址
./^[a-zA-z]+://(\w+(-\w+)*)(\.(\w+(-\w+)*))*(\?\S*)?$/;
.或:^http:\/\/[A-Za-z-]+\.[A-Za-z-]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*
.//年/月/日(年-月-日、年.月.日)
./^(|)\d\d[/.]([-]|[])[/.]([-]|[][-]|[])$/;
.//匹配中文字符
./[\ue-\ufa]/;
.//匹配帳號是否合法(字母開頭,允許-字節,允許字母數字下劃線)
./^[a-zA-Z][a-zA-Z-_]{,}$/;
.//匹配空白行的正則表達式
./\n\s*\r/;
.//匹配中國郵政編碼
./[-]\d{}(?!\d)/;
.//匹配身份證
./\d{}|\d{}/;
.//匹配國內電話號碼
./(\d{}-|\d{}-)?(\d{}|\d{})?/;
.//匹配IP地址
./(([-]\d|[-]|[]?\d\d?)\.){}([-]\d|[-]|[]?\d\d?)/;
.//匹配首尾空白字符的正則表達式
./^\s*|\s*$/;
.//匹配HTML標記的正則表達式
.(\S*?)[^>]*>.*?|.*/>;
.//sq語句
.^(select|drop|delete|create|update|insert).*$
.//提取信息中的網絡鏈接
.(h|H)(r|R)(e|E)(f|F**('|")?(\w|\\|\/|\.)+('|"*|>)?
.//提取信息中的郵件地址
.\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
.//提取信息中的圖片鏈接
.(s|S)(r|R)(c|C**('|")?(\w|\\|\/|\.)+('|"*|>)?
.//提取信息中I地址
.(\d+)\.(\d+)\.(\d+)\.(\d+)
.//取信息中的中國手機號碼
.()**\d{}
.//提取信息中的中國郵政編碼
.[-]{}(\d+){}
.//提取信息中的浮點數(即小數)
.(-?\d*)\.?\d+
.//提取信息中的任何數字
.(-?\d*)(\.\d+)?
.//電話區號
.^\d{,}$
.//騰Q號
.^[-]*[-][-]*
.//帳號(字母開頭,允-字節,允許字母數字下劃線)
.^[a-zA-Z][a-zA-Z-_]{,}
.//中文、英文、數字及下劃線
.^[\ue-\ufa_a-zA-Z-]+$
返回頂部的通用方法
.functiobackTop(btnId{
vabtdocument.getElementById(btnId);
vadocument.documentElement;
vadocument.body;
window.onscrolset;
btn.style.displa"none";
btn.onclicfunction({
btn.style.displa"none";
window.onscrolnull;
this.timesetInterval(function({
d.scrollTo-Math.ceil((d.scrollTob.scrollTop.);
b.scrollTo-Math.ceil((d.scrollTob.scrollTop.);
i((d.scrollTob.scrollTop=clearInterval(btn.timerwindow.onscrolset);
});
};
functioset({
btn.style.displa(d.scrollTob.scrollTo'block'"none"
}
.};
.backTop('goTop');
獲得URL中GET參數值
./用法:如果地址test.htm?t=&t=&t=那麼能取得:GET["t"]GET["t"]GET["t"]
.functioget_get(){
querystwindow.location.href.split("?")
if(querystr[]){
GETquerystr[].split("&");
GE[];
for(i=;i<GETs.length;i++){
tmp_arGETs.split("=")
key=tmp_arr[]
GET[keytmp_arr[]
}
}
returquerystr[];
.}
打開一個窗體通用方法
.functioopenWindow(url,windowName,width,height){
vaparseInt(screen.widt.(widt.);
vaparseInt(screen.heigh.(heigh.);
vaisMSIE(navigator.appNam="MicrosofInterneExplorer");
i(isMSIE{
va"resizable=,location=no,scrollbars=no,width=";
p+width;
p+",height=";
p+height;
p+",left=";
p+x;
p+",top=";
p+y;
retvawindow.open(urlwindowNamep);
els{
vawiwindow.open(url"ZyiisPopup""top=",left=",scrollbars=scrollbar",dialog=yes,modal=yes,width=widt",height=heigh",resizable=no);
eval("trwin.resizeTo(widthheight)catch(e}");
win.focus();
}
.}
提取頁面代碼中所有網址
vaadocument.documentElement.outerHTML.match(/(url\(|src=|href=)[\"\']*([^\"\'\(\)\<\>\[\]+)[\"\'\)]*|(http:\/\/[\w\-\.]+[^\"\'\(\)\<\>\[\]+)/ig).join("\r\n").replace(/^(src=|href=|url\()[\"\']*|[\"\'\>\]*$/igm,"");
alert(aa);
清除相同的數組
String.prototype.unique=function(){
vax=this.split(/[\r\n]+/);
vay='';
for(vai=;i<x.length;i++){
if(!neRegExp("^"+x.replace(/([^\w])/ig,"\\$")+"$","igm").test(y)){
y+=x+"\r\n"
}
}
retury
};
按字母排序,對每行進行數組排序
functioSetSort(){
vatext=K.value.split(/[\r\n]/).sort().join("\r\n");//順序
vatest=K.value.split(/[\r\n]/).sort().reverse().join("\r\n");//反序
K.value=K.value!=text?text:test;
}
字符串反序
functioIsReverse(text){
returtext.split('').reverse().join('');
}
清除html代碼中的腳本
functioclear_script(){
K.value=K.value.replace(/<script.*?>[\s\S]*?<\/script>|\s+on[a-zA-Z]{,}\s?=\s?"[\s\S]*?"|\s+on[a-zA-Z]{,}\s?=\s?'[\s\S]*?'|\s+on[a-zA-Z]{,}\s?=[>]+/ig,"");
}
動態執行JavaScript腳本
functiojavascript(){
try{
eval(K.value);
}catch(e){
alert(e.message);
}
}
動態執行VBScript腳本
functiovbscript(){
try{
vascript=document.getElementById("K").value;
if(script.trim()=="")return;
window.execScript('OErroResumNex\n'+script+'\IErr.Number<>The\MsgBo"請輸入正確的VBScript腳本!",,"腳本錯誤!\EnIf',"vbscript")
}catch(e){
alert(e.message);
}
}
金額大寫轉換函數
functiotransform(tranvalue{
tr{
va;
vadneArray("""萬""億")//大單位
vadneArray("拾""佰""仟")//小單位
vadneArray("零""壹""貳""三""肆""伍""陸""柒""捌""玖")//整數部分用
//以下是小寫轉換成大寫顯示在合計大寫的文本框
//分離整數與小數
vasourcsplits(tranvalue);
vanusource[];
vadisource[];
//轉換整數部分
va//計小單位
va//計大單位
vasu;
vast"";
valesource[].length//整數的長度
fo(<leni++{
vasource[].charAt(lei)//取得某個位數上的數字
vab;
i(l>{
bsource[].charAt(le)//取得某個位數前一位上的數字
}
susuNumber(n);
i(su!{
stdw[Number(n)].concat(str)//取得該數字對應的大寫數字,並插入到str字符串的前面
i(=''su;
}
i(l>//在數字范圍內
i(!//加小單位
i(b!{
stdw[k].concat(str);
}
k++;
els//不加小單位,加大單位
;
vatemstr.charAt();
i(tem="萬|tem="億"//若大單位前沒有數字則捨去大單位
ststr.substr(str.lengt);
stdw[k].concat(str);
su;
}
}
i(=)//小單位到千則大單位進一
k++;
}
}
//轉換小數部分
vastrdi"";
i(di!""{
vadig.charAt();
i(!{
strdi+dw[Number(n)"角"//加數字
}
vadig.charAt();
i(!{
strdi+dw[Number(n)"分"//加數字
}
}
st+"元strdig;
catch(e{
retur"元";
}
returstr;
}
//拆分整數與小數
functiosplits(tranvalue{
vavaluneArray('''');
temtranvalue.split(".");
fo(vatemp.lengthi++{
valutemp;
}
returvalue;
}
resize的操作
(function(){
vaffunction(){
vadocument.documentElemendocument.documentElement.clientWidtdocument.body.clientWidth
,
,Element.extend(document.body)
,classnamb.className;
if(r){
//當窗體的寬度小於的時候執行相應的操作
}else{
//當窗體的寬度大於的時候執行相應的操作
}
}
if(window.addEventListener){
window.addEventListener('resize'function()fn()});
}elsif(window.attachEvent){
window.attachEvent('onresize'function()fn()});
}
fn();
})();
實現base64解碼
functiobase_decode(data){
vab"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/=";
vaooohhhhbits,a,de"",tmp_ar[];
i(!datareturdata}
dat+'';
d{
hb.indexOf(data.charAt(i++));
hb.indexOf(data.charAt(i++));
hb.indexOf(data.charAt(i++));
hb.indexOf(data.charAt(i++));
bith<h<h<h;
obit>xff;
obit>xff;
obitxff;
i(h={
tmp_arr[ac++String.fromCharCode(o);
elsi(h={
tmp_arr[ac++String.fromCharCode(oo);
els{
tmp_arr[ac++String.fromCharCode(ooo);
}
whil(data.length);
detmp_arr.join('');
deutf_decode(dec);
returdec;
}
實現utf8解碼
.functioutf_decode(str_data){
vatmp_ar[],,a,,,;str_dat+'';
whil(str_data.length{
str_data.charCodeAt(i);
i({
tmp_arr[ac++String.fromCharCode(c);
i++;
elsi&{
str_data.charCodeAt();
tmp_arr[ac++String.fromCharCode(((<());
+;
els{
str_data.charCodeAt();
str_data.charCodeAt();
tmp_arr[ac++String.fromCharCode(((<((<());
+;
}
}
returtmp_arr.join('');
}
獲取窗體可見范圍的寬與高
.functiogetViewSize(){
vade=document.documentElement;
vadb=document.body;
vaviewW=de.clientWidth==db.clientWidtde.clientWidth;
vaviewH=de.clientHeight==db.clientHeighde.clientHeight;
returArray(view,viewH);
}
斷鼠標是否移出事件
functioisMouseOut(ehandler{
i(e.typ!='mouseout'{
returfalse;
}
varelte.relatedTargee.relatedTargee.typ=='mouseoute.toElemene.fromElement;
whil(relt&relt!=handler{
reltreltg.parentNode;
}
retur(relt!=handler);
}
半角轉換為全角函數
.functioToDBC(str){
varesul'';
for(vai=str.lengthi++){
codstr.charCodeAt(i);
if(cod>&cod<){
resul+String.fromCharCode(str.charCodeAt(i);
}elsi(cod=){
resul+String.fromCharCode(str.charCodeAt(i);
}else{
resul+str.charAt(i);
}
}
returresult;
}
全角轉換為半角函數
.functioToCDB(str){
varesul'';
for(vai=str.lengthi++){
codstr.charCodeAt(i);
if(cod&cod<){
resul+String.fromCharCode(str.charCodeAt(i);
}elsi(cod=){
resul+String.fromCharCode(str.charCodeAt();
}else{
resul+str.charAt(i);
}
}
returresult;
}