只能输入数字的输入框(input)例子

来源:互联网 发布:java 高并发框架 编辑:程序博客网 时间:2024/05/23 02:13
<script type="text/javascript"><!--google_ad_client = "pub-4490194096475053";/* 内容页,300x250,第一屏 */google_ad_slot = "3685991503";google_ad_width = 300;google_ad_height = 250;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
代码:

/* 
 * zhanjh 2008.06.04
 */
function NumInput(){
    var input=document.createElement("input");
    input.type="text";
    var oThis=this;
    input.onkeydown=function(e){
        var keycode=(e)?e.which:event.keyCode;
        if(!oThis.isNumberKeyCode(keycode)){
            oThis.cancelEvent(e);
            return;
        }
    }
    return input
}
NumInput.prototype={
    /**
     * 取消事件
     */
    cancelEvent:function(e){
        if(e&&e.preventDefault){
            e.preventDefault();
            e.stopPropagation();
        }else{
            event.cancelBubble=true;
            event.returnValue=false;
        }
        return false;
    },
    /**
     * 判断是否是数字键
     */
    isNumberKeyCode:function(keycode){
        if(keycode>=48&&keycode<=57)
            return true;
        else if(keycode>=96&&keycode<=105)
            return true;
        else if(keycode==8||keycode==13||keycode==9||keycode==46)
            return true;
        else if(keycode<=40&&keycode>=37)
            return true;
        return false;
    }
}


使用:

function addNumInput(){

   var input=new NumInput();

    document.body.appendChild(input);

}
原创粉丝点击