JavaScript在ASP中實現(xiàn)掩碼文本框

字號:

在網(wǎng)頁中輸日期、時間、IP地址等需要一定的格式限制,否則將會程序將會很難和程序溝通。
    最近在做一個程序正好需要用到此方面,在網(wǎng)上找到過相應的程序,但用起來都非常惡,于是乎只好自己實現(xiàn)一個了。
    首先實現(xiàn)兩個函數(shù)用來操作光標:
    // 得到一個文本框控件的當前光標位置
    function getPos(obj)
    {
    obj.focus();
    var workRange=document.selection.createRange();
    obj.select();
    var allRange=document.selection.createRange();
    workRange.setEndPoint( "StartToStart",allRange);
    var len=workRange.text.length;
    workRange.collapse(false);
    workRange.select();
    return len;
    }
    // 設置一個文本框控件的當前光標位置
    function setCursor(obj,num){
    range=obj.createTextRange();
    range.collapse(true);
    range.moveStart('character',num);
    range.select();
    }
    主要函數(shù)實現(xiàn)的主要思想是當鍵盤按下時進行一些操作,我設計在onKeyDown事件中。
    在onKeyDown中,首先將系統(tǒng)默認的鍵盤處理屏蔽掉
    // 封住傳統(tǒng)處理
    window.event.returnvalue = false;
    然后處理相應需要處理的鍵盤消息。
    這里隨便處理幾個必要的就可以了,因為文本框本身也不需要什么太多的用戶操作,所以把光標的前移、后移、刪除操作進行處理,這樣你的文本框就有了基本的操作,現(xiàn)在操作起來已經(jīng)很順手了。
    // 自行處理按鈕
    switch (nKeyCode)
    {
    case 8:// 如果動作是退格[ <-]
    {
    strText = strText.substr(0,nCursorPos-1) + strText.substr(nCursorPos, nTextLen-nCursorPos);
    nCursorPos--;
    break;
    }
    case 46:// 如果動作是del[del]
    {
    strText = strText.substr(0,nCursorPos) + strText.substr(nCursorPos+1,nTextLen-nCursorPos-1);
    nCursorPos--;
    break;
    }
    case 38:// 如果動作是方向鍵[上]
    case 39:// 如果動作是方向鍵[右]
    {
    nCursorPos++;
    break;
    }
    case 37:// 如果動作是方向鍵[左]
    case 40:// 如果動作是方向鍵[下]
    {
    nCursorPos--;
    break;
    }
    default :
    {
    strText = strText.substr(0,nCursorPos) + String.fromCharCode(nKeyCode) + strText.substr(nCursorPos,nTextLen);
    nCursorPos++;
    if (nCursorPos >strText.length)
    {
    nCursorPos=strText.length;
    }
    break;
    }
    }
    其它的任何消息都當添加一個字符,可見不可見的字符,都將添加并光標往后走一下。見上方的default 處理部份。
    然后判斷掩碼是否正確,如果正確,那么此次輸入合法,將值顯示添加到文本框中。
    if (strText.match(expMask))
    {
    // 輸入格式正確
    objTextBox.value = strText;
    }
    最后將光標移到適當?shù)奈恢谩?BR>    // 移動光標
    setCursor(objTextBox,nCursorPos);
    完成!