代码:
/*
*zhanjh2008.06.04
*/
functionNumInput(){
varinput=document.createElement("input");
input.type="text";
varoThis=this;
input.onkeydown=function(e){
varkeycode=(e)?e.which:event.keyCode;
if(!oThis.isNumberKeyCode(keycode)){
oThis.cancelEvent(e);
return;
}
}
returninput
}
NumInput.prototype={
/**
*取消事件
*/
cancelEvent:function(e){
if(e&&e.preventDefault){
e.preventDefault();
e.stopPropagation();
}else{
event.cancelBubble=true;
event.returnValue=false;
}
returnfalse;
},
/**
*判断是否是数字键
*/
isNumberKeyCode:function(keycode){
if(keycode>=48&&keycode<=57)
returntrue;
elseif(keycode>=96&&keycode<=105)
returntrue;
elseif(keycode==8||keycode==13||keycode==9||keycode==46)
returntrue;
elseif(keycode<=40&&keycode>=37)
returntrue;
returnfalse;
}
}
使用:
functionaddNumInput(){
varinput=newNumInput();
document.body.appendChild(input);
}
/*
*zhanjh2008.06.04
*/
functionNumInput(){
varinput=document.createElement("input");
input.type="text";
varoThis=this;
input.onkeydown=function(e){
varkeycode=(e)?e.which:event.keyCode;
if(!oThis.isNumberKeyCode(keycode)){
oThis.cancelEvent(e);
return;
}
}
returninput
}
NumInput.prototype={
/**
*取消事件
*/
cancelEvent:function(e){
if(e&&e.preventDefault){
e.preventDefault();
e.stopPropagation();
}else{
event.cancelBubble=true;
event.returnValue=false;
}
returnfalse;
},
/**
*判断是否是数字键
*/
isNumberKeyCode:function(keycode){
if(keycode>=48&&keycode<=57)
returntrue;
elseif(keycode>=96&&keycode<=105)
returntrue;
elseif(keycode==8||keycode==13||keycode==9||keycode==46)
returntrue;
elseif(keycode<=40&&keycode>=37)
returntrue;
returnfalse;
}
}
使用:
functionaddNumInput(){
varinput=newNumInput();
document.body.appendChild(input);
}
本文介绍了一种使用JavaScript实现仅允许数字输入的自定义输入框的方法。通过创建一个名为NumInput的功能性对象,该对象可以生成一个只接受数字键输入的文本框。此功能通过监听键盘事件并检查按键代码来实现,确保只有数字键、退格键、删除键、方向键和回车键能够触发输入行为。
460

被折叠的 条评论
为什么被折叠?



