javascript

位置:IT落伍者 >> javascript >> 浏览文章

javascript常用代码大全


发布日期:2021年12月24日
 
javascript常用代码大全

//打开模式对话框

function doSelectUser(txtId)

{

strFeatures=dialogWidth=px;dialogHeight=px;center=yes;

middle=yes ;help=no;status=no;scroll=no;

var urlstrReturn;

url=selUseraspx;

strReturn=windowshowModalDialog(urlstrFeatures);

//返回模式对话框的值

function okbtn_onclick()

{

var commstr=;

windowreturnValue=commstr;

windowclose() ;

}

全屏幕打开 IE 窗口

var winWidth=screenavailWidth ;

var winHeight=screenavailHeight;

windowopen(mainaspxsurveyWindowtoolbar=nowidth=+ winWidth +height=+ winHeight +top=left=scrollbars=yesresizable=yescenter:yesstatusbars=yes);

break

//脚本中中使用xml

function initialize() {

var xmlDoc

var xslDoc

xmlDoc = new ActiveXObject(MicrosoftXMLDOM)

xmlDocasync = false;

xslDoc = new ActiveXObject(MicrosoftXMLDOM)

xslDocasync = false;

xmlDocload(treexml)

xslDocload(treexsl)

folderTreeinnerHTML = xmlDocdocumentElementtransformNode(xslDoc)

}

验证类

数字验证内

整数

大于的整数 (用于传来的ID的验证)

负整数的验证

整数不能大于iMax

整数不能小于iMin

时间类

短时间形如 (::)

短日期形如 ()

长时间形如 ( ::)

只有年和月形如(或者)

只有小时和分钟形如(:)

表单类

所有的表单的值都不能为空

多行文本框的值不能为空

多行文本框的值不能超过sMaxStrleng

多行文本框的值不能少于sMixStrleng

判断单选框是否选择

判断复选框是否选择

复选框的全选多选全不选反选

文件上传过程中判断文件类型

字符类

判断字符全部由aZ或者是AZ的字字母组成

判断字符由字母和数字组成

判断字符由字母和数字下划线点号组成且开头的只能是下划线和字母

字符串替换函数Replace();

浏览器类

判断浏览器的类型

判断ie的版本

判断客户端的分辨率

结合类

email的判断

手机号码的验证

身份证的验证

时间与相关控件类

日历

时间控件

万年历

显示动态显示时钟效果(文本如OA中时间)

显示动态显示时钟效果 (图像像手表)

表单类

自动生成表单

动态添加修改删除下拉框中的元素

可以输入内容的下拉框

多行文本框中只能输入iMax文字如果多输入了自动减少到iMax个文字(多用于短信发送)

打印类

打印控件

事件类

屏蔽右键

屏蔽所有功能键

> 和< F FFF

屏蔽组合键ctrl+N

网页设计类

连续滚动的文字图片(注意是连续的两段文字和图片中没有空白出现)

html编辑控件类

颜色选取框控件

下拉菜单

两层或多层次的下拉菜单

仿IE菜单的按钮(效果如的导航栏目)

状态栏title栏的动态效果(例子很多可以研究一下)

双击后网页自动滚屏

树型结构

asp+SQL版

asp+xml+sql版

java+sql或者java+sql+xml

无边框效果的制作

连动下拉框技术

文本排序

画图类含饼矢量贝滋曲线

操纵客户端注册表类

DIV层相关(拖拽显示隐藏移动增加)

TABLAE相关(客户端动态增加行列模拟进度条滚动列表等)

各种<object classid=>相关类如播放器flash与脚本互动等

刷新/模拟无刷新 异步调用类(XMLHttp或iframeframe)

验证类

数字验证内

整数

/^(|\+)?\d+$/test(str)

大于的整数 (用于传来的ID的验证)

/^\d+$/test(str)

负整数的验证

/^\d+$/test(str)

时间类

短时间形如 (::)

function isTime(str)

{

var a = strmatch(/^(\d{})(:)?(\d{})\(\d{})$/);

if (a == null) {alert(输入的参数不是时间格式); return false;}

if (a[]> || a[]> || a[]>)

{

alert(时间格式不对);

return false

}

return true;

}

短日期形如 ()

function strDateTime(str)

{

var r = strmatch(/^(\d{})(|\/)(\d{})\(\d{})$/);

if(r==null)return false;

var d= new Date(r[] r[] r[]);

return (dgetFullYear()==r[]&&(dgetMonth()+)==r[]&&dgetDate()==r[]);

}

长时间形如 ( ::)

function strDateTime(str)

{

var reg = /^(\d{})(|\/)(\d{})\(\d{}) (\d{}):(\d{}):(\d{})$/;

var r = strmatch(reg);

if(r==null)return false;

var d= new Date(r[] r[]r[]r[]r[]r[]);

return (dgetFullYear()==r[]&&(dgetMonth()+)==r[]&&dgetDate()==r[]&&dgetHours()==r[]&&dgetMinutes()==r[]&&dgetSeconds()==r[]);

}

只有年和月形如(或者)

只有小时和分钟形如(:)

表单类

所有的表单的值都不能为空

<input onblur=if(thisvaluereplace(/^\s+|\s+$/g)==)alert(不能为空!)>

多行文本框的值不能为空

多行文本框的值不能超过sMaxStrleng

多行文本框的值不能少于sMixStrleng

判断单选框是否选择

判断复选框是否选择

复选框的全选多选全不选反选

文件上传过程中判断文件类型

字符类

判断字符全部由aZ或者是AZ的字字母组成

<input onblur=if(/[^azAZ]/gtest(thisvalue))alert(有错)>

判断字符由字母和数字组成

<input onblur=if(/[^azAZ]/gtest(thisvalue))alert(有错)>

判断字符由字母和数字下划线点号组成且开头的只能是下划线和字母

/^([azAz_]{})([\w]*)$/gtest(str)

字符串替换函数Replace();

浏览器类

判断浏览器的类型

windownavigatorappName

判断ie的版本

windownavigatorappVersion

判断客户端的分辨率

windowscreenheight; windowscreenwidth;

结合类

email的判断

function ismail(mail)

{

return(new RegExp(/^\w+((\w+)|(\\w+))*\@[AZaz]+((\|)[AZaz]+)*\[AZaz]+$/)test(mail));

}

手机号码的验证

身份证的验证

function isIdCardNo(num)

{

if (isNaN(num)) {alert(输入的不是数字!); return false;}

var len = numlength re;

if (len == )

re = new RegExp(/^(\d{})()?(\d{})(\d{})(\d{})(\d{})$/);

else if (len == )

re = new RegExp(/^(\d{})()?(\d{})(\d{})(\d{})(\d{})(\d)$/);

else {alert(输入的数字位数不对!); return false;}

var a = nummatch(re);

if (a != null)

{

if (len==)

{

var D = new Date(+a[]+/+a[]+/+a[]);

var B = DgetYear()==a[]&&(DgetMonth()+)==a[]&&DgetDate()==a[];

}

else

{

var D = new Date(a[]+/+a[]+/+a[]);

var B = DgetFullYear()==a[]&&(DgetMonth()+)==a[]&&DgetDate()==a[];

}

if (!B) {alert(输入的身份证号 + a[] + 里出生日期不对!); return false;}

}

return true;

}

画图:

<OBJECT

id=S

height=

width=

classid=clsid:CDACDDACE>

</OBJECT>

<SCRIPT>

SDrawingSurfaceArcDegrees();

SDrawingSurfaceArcRadians();

SDrawingSurfaceLine();

</SCRIPT>

写注册表

<SCRIPT>

var WshShell = WScriptCreateObject(WScriptShell);

WshShellRegWrite (HKCU\\Software\\ACME\\FortuneTeller\\ REG_BINARY);

WshShellRegWrite (HKCU\\Software\\ACME\\FortuneTeller\\MindReader Goocher! REG_SZ);

var bKey = WshShellRegRead (HKCU\\Software\\ACME\\FortuneTeller\\);

WScriptEcho (WshShellRegRead (HKCU\\Software\\ACME\\FortuneTeller\\MindReader));

WshShellRegDelete (HKCU\\Software\\ACME\\FortuneTeller\\MindReader);

WshShellRegDelete (HKCU\\Software\\ACME\\FortuneTeller\\);

WshShellRegDelete (HKCU\\Software\\ACME\\);

</SCRIPT>

TABLAE相关(客户端动态增加行列)

<HTML>

<SCRIPT LANGUAGE=JScript>

function numberCells() {

var count=;

for (i=; i < documentallmytablerowslength; i++) {

for (j=; j < documentallmytablerows(i)cellslength; j++) {

documentallmytablerows(i)cells(j)innerText = count;

count++;

}

}

}

</SCRIPT>

<BODY onload=numberCells()>

<TABLE id=mytable border=>

<TR><TH>&nbsp;</TH><TH>&nbsp;</TH><TH>&nbsp;</TH><TH>&nbsp;</TH></TR>

<TR><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD></TR>

<TR><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD></TR>

</TABLE>

</BODY>

</HTML>

1.身份证严格验证

<script>

var aCity={:北京:天津:河北:山西:内蒙古:辽宁:吉林:黑龙江:上海:江苏:浙江:安徽:福建:江西:山东:河南:湖北:湖南:广东:广西:海南:重庆:四川:贵州:云南:西藏:陕西:甘肃:青海:宁夏:新疆:台湾:香港:澳门:国外}

function cidInfo(sId){

var iSum=

var info=

if(!/^\d{}(\d|x)$/itest(sId))return false;

sId=sIdreplace(/x$/ia);

if(aCity[parseInt(sIdsubstr())]==null)return Error:非法地区;

sBirthday=sIdsubstr()++Number(sIdsubstr())++Number(sIdsubstr());

var d=new Date(sBirthdayreplace(//g/))

if(sBirthday!=(dgetFullYear()++ (dgetMonth()+) + + dgetDate()))return Error:非法生日;

for(var i = ;i>=;i ) iSum += (Mathpow(i) % ) * parseInt(sIdcharAt( i))

if(iSum%!=)return Error:非法证号;

return aCity[parseInt(sIdsubstr())]++sBirthday++(sIdsubstr()%?:)

}

documentwrite(cidInfo()<br/>);

documentwrite(cidInfo()<br/>)

documentwrite(cidInfo()<br/>)

documentwrite(cidInfo(x)<br/>);

</script>

2.验证IP地址

<SCRIPT LANGUAGE=JavaScript>

function isip(s){

var check=function(v){try{return (v<= && v>=)}catch(x){return false}};

var re=ssplit()

return (relength==)?(check(re[]) && check(re[]) && check(re[]) && check(re[])):false

}

var s=;

alert(isip(s))

</SCRIPT>

3.加sp后还能用的无边框窗口!!

<HTML XMLNS:IE>

<meta httpequiv=ContentType content=text/html; charset=gb>

<IE:Download ID=include STYLE=behavior:url(#default#download) />

<title>Chromeless Window</title>

<SCRIPT LANGUAGE=JScript>

/* Special Thanks For andot */

/*

This following code are designed and writen by Windy_sk <>

You can use it freely but u must held all the copyright items!

*/

/* Thanks For andot Again */

var CW_width= ;

var CW_height= ;

var CW_top= ;

var CW_left= ;

var CW_url= /;

var New_CW= windowcreatePopup();

var CW_Body= New_CWdocumentbody;

var content= ;

var CSStext= margin:px;color:black; border:px outset;borderstyle:expression(onmouseout=onmouseup=function(){thisstyleborderStyle=outset} onmousedown=function(){if(eventbutton!=)thisstyleborderStyle=inset});backgroundcolor:buttonface;width:px;height:px;fontsize:px;lineheight:px;cursor:Default;;

//Build Window

includestartDownload(CW_url function(source){content=source});

function insert_content(){

var temp = ;

CW_Bodystyleoverflow= hidden;

CW_BodystylebackgroundColor= white;

CW_Bodystyleborder= solid black px;

content = contentreplace(/<a ([^>]*)>/g<a onclick=parentopen(thishref);return false $>);

temp += <table width=% height=% cellpadding= cellspacing= border=>;

temp += <tr style=;fontsize:px;background:#CC;height:;cursor:default ondblclick=\MaxinnerText=MaxinnerText==?:;parentif_max=!parentif_max;parentshow_CW();\ onmouseup=parentdrag_up(event) onmousemove=parentdrag_move(event) onmousedown=parentdrag_down(event) onselectstart=return false oncontextmenu=return false>;

temp += <td style=color:#ffffff;paddingleft:px>Chromeless Window For IE SP</td>;

temp += <td style=color:#ffffff;paddingright:px; align=right>;

temp += <span id=Help onclick=\alert(Chromeless Window For IE SP Ver \\n\\nCode By Windy_sk\\n\\nSpecial Thanks For andot)\ style=\+CSStext+fontfamily:System;paddingright:px;\>?</span>;

temp += <span id=Min onclick=parentNew_CWhide();parentblur() style=\+CSStext+fontfamily:Webdings;\ title=Minimum></span>;

temp += <span id=Max onclick=\thisinnerText=thisinnerText==?:;parentif_max=!parentif_max;parentshow_CW();\ style=\+CSStext+fontfamily:Webdings;\ title=Maximum></span>;

temp += <span id=Close onclick=parentopener=null;parentclose() style=\+CSStext+fontfamily:System;paddingright:px;\ title=Close>x</span>;

temp += </td></tr><tr><td colspan=>;

temp += <div id=include style=overflow:scroll;overflowx:hidden;overflowy:auto; HEIGHT: %; width:+CW_width+>;

temp += content;

temp += </div>;

temp += </td></tr></table>;

CW_BodyinnerHTML = temp;

}

setTimeout(insert_content());

var if_max = true;

function show_CW(){

windowmoveTo( );

if(if_max){

New_CWshow(CW_top CW_left CW_width CW_height);

if(typeof(New_CWdocumentallinclude)!=undefined){

New_CWdocumentallincludestylewidth = CW_width;

New_CWdocumentallMaxinnerText = ;

}

}else{

New_CWshow( screenwidth screenheight);

New_CWdocumentallincludestylewidth = screenwidth;

}

}

windowonfocus = show_CW;

windowonresize = show_CW;

// Move Window

var drag_xdrag_ydraging=false

function drag_move(e){

if (draging){

New_CWshow(escreenXdrag_x escreenYdrag_y CW_width CW_height);

return false;

}

}

function drag_down(e){

if(ebutton==)return;

if(New_CWdocumentbodyoffsetWidth==screenwidth && New_CWdocumentbodyoffsetHeight==screenheight)return;

drag_x=eclientX;

drag_y=eclientY;

draging=true;

esrcElementsetCapture();

}

function drag_up(e){

draging=false;

esrcElementreleaseCapture();

if(New_CWdocumentbodyoffsetWidth==screenwidth && New_CWdocumentbodyoffsetHeight==screenheight) return;

CW_top = escreenXdrag_x;

CW_left = escreenYdrag_y;

}

</SCRIPT>

</HTML>

贴两个关于treeview的

<script language=javascript>

<!

//初始化选中节点

function initchecknode()

{

var node=TreeViewgetTreeNode();

nodesetAttribute(Checkedtrue);

setcheck(nodetrue);

FindCheckedFromNode(TreeView);

}

//oncheck事件

function tree_oncheck(tree)

{

var node=treegetTreeNode(treeclickedNodeIndex);

var Pchecked=treegetTreeNode(treeclickedNodeIndex)getAttribute(checked);

setcheck(nodePchecked);

documentallcheckedvalue=;

documentalluncheckedvalue=;

FindCheckedFromNode(TreeView);

}

//设置子节点选中

function setcheck(nodePc)

{

var i;

var ChildNode=new Array();

ChildNode=nodegetChildren();

if(parseInt(ChildNodelength)==)

return;

else

{

for(i=;i<ChildNodelength;i++)

{

var cNode;

cNode=ChildNode[i];

if(parseInt(cNodegetChildren()length)!=)

setcheck(cNodePc);

cNodesetAttribute(CheckedPc);

}

}

}

//获取所有节点状态

function FindCheckedFromNode(node) {

var i = ;

var nodes = new Array();

nodes = nodegetChildren();

for (i = ; i < nodeslength; i++) {

var cNode;

cNode=nodes[i];

if (cNodegetAttribute(Checked))

AddChecked(cNode);

else

AddUnChecked(cNode);

if (parseInt(cNodegetChildren()length) != ) {

FindCheckedFromNode(cNode);

}

}

}

//添加选中节点

function AddChecked(node) {

documentallcheckedvalue += nodegetAttribute(NodeData);

documentallcheckedvalue += ;

}

//添加未选中节点

function AddUnChecked(node) {

documentalluncheckedvalue += nodegetAttribute(NodeData);

documentalluncheckedvalue += ;

}

//>

</script>

treeview中如何在服务器端得到客户端设置后的节点选中状态

<script language=C# runat=server>

private void Button_Click(object sender SystemEventArgs e)

{

ResponseWrite(TreeViewNodes[]Checked);

}

</script>

<script language=javascript>

function set_check()

{

var nodeindex = ;

var node=TreeViewgetTreeNode(nodeindex);

nodesetAttribute(CheckedTrue);

TreeViewqueueEvent(oncheck nodeindex);

}

</script>

三个实用的小技巧:关闭输入法禁止贴上禁止複製

关闭输入法

本文字框输入法被关闭

语法  

範例 <input type=text name=textfield >

本文字框禁止贴上文字

语法onpaste=return false

範例<input type=text name=textfield onpaste=return false>

本文字框禁止複製

语法oncopy=return false; oncut=return false;

範例<input name=textfield type=text value=不能複製里面的字 oncopy=return false; oncut=return false;>

//================================

//Cookie操作

//================================

function getCookieVal (offset)

{

var endstr = okieindexOf (; offset);

if (endstr == )

endstr = okielength;

return unescape(okiesubstring(offset endstr));

}

function GetCookie (name)

{

var arg = name + =;

var alen = arglength;

var clen = okielength;

var i = ;

while (i < clen)

{

var j = i + alen;

if (okiesubstring(i j) == arg)

return getCookieVal (j);

i = okieindexOf( i) + ;

if (i == )

break;

}

return null;

}

function deleteCookie(cname) {

var expdate = new Date();

expdatesetTime(expdategetTime() ( * * * * ));

// okie = ckValue=ok; expires=+ expdatetoGMTString();

setCookie(cnameexpdate);

function setCookie (name value expires) {

okie = name + = + escape(value) +

; expires= + expirestoGMTString() ;

}

一个可以在页面上随意画线多边形填充等功能的js (part

var jg_ihtm jg_ie jg_fast jg_dom jg_moz

jg_n = (documentlayers && typeof documentclasses != undefined);

function chkDHTM(x i)

{

x = documentbody || null;

jg_ie = x && typeof xinsertAdjacentHTML != undefined;

jg_dom = (x && !jg_ie &&

typeof xappendChild != undefined &&

typeof documentcreateRange != undefined &&

typeof (i = documentcreateRange())setStartBefore != undefined &&

typeof icreateContextualFragment != undefined);

jg_ihtm = !jg_ie && !jg_dom && x && typeof xinnerHTML != undefined;

jg_fast = jg_ie && documentall && !windowopera;

jg_moz = jg_dom && typeof xstyleMozOpacity != undefined;

}

function pntDoc()

{

thiswnddocumentwrite(jg_fast? Rpc() : );

= ;

}

function pntCnvDom()

{

var x = documentcreateRange();

xsetStartBefore(v);

x = xcreateContextualFragment(jg_fast? Rpc() : );

vappendChild(x);

= ;

}

function pntCnvIe()

{

vinsertAdjacentHTML(BeforeEnd jg_fast? Rpc() : );

= ;

}

function pntCnvIhtm()

{

vinnerHTML += ;

= ;

}

function pntCnv()

{

= ;

}

function mkDiv(x y w h)

{

+= <div ><\/div>;

}

function mkDivIe(x y w h)

{

+= %%+lor+;+x+;+y+;+w+;+h+;;

}

function mkDivPrt(x y w h)

{

+= <div ><\/div>;

}

function mkLyr(x y w h)

{

+= <layer +

left= + x + +

top= + y + +

width= + w + +

height= + h + +

bgcolor= + lor + ><\/layer>\n;

}

var regex = /%%([^;]+);([^;]+);([^;]+);([^;]+);([^;]+);/g;

function htmRpc()

{

return replace(

regex

<div ></div>\n);

}

function htmPrtRpc()

{

return replace(

regex

<div ></div>\n);

}

function mkLin(x y x y)

{

if (x > x)

{

var _x = x;

var _y = y;

x = x;

y = y;

x = _x;

y = _y;

}

var dx = xx dy = Mathabs(yy)

x = x y = y

yIncr = (y > y)? : ;

if (dx >= dy)

{

var pr = dy<<

pru = pr (dx<<)

p = prdx

ox = x;

while ((dx) > )

{

++x;

if (p > )

{

thismkDiv(ox y xox );

y += yIncr;

p += pru;

ox = x;

}

else p += pr;

}

thismkDiv(ox y xox+ );

}

else

{

var pr = dx<<

pru = pr (dy<<)

p = prdy

oy = y;

if (y <= y)

{

while ((dy) > )

{

if (p > )

{

thismkDiv(x++ y oyy+);

y += yIncr;

p += pru;

oy = y;

}

else

{

y += yIncr;

p += pr;

}

}

thismkDiv(x y oyy+);

}

else

{

while ((dy) > )

{

y += yIncr;

if (p > )

{

thismkDiv(x++ oy yoy);

p += pru;

oy = y;

}

else p += pr;

}

thismkDiv(x oy yoy+);

}

}

}               

上一篇:用JS快速保存网页中所有图片的方法

下一篇:js 固定悬浮效果实现思路代码