Event.keyCode控制input只能輸入數字

來源:互聯網
上載者:User

標籤:event.keycode

<script>

    function onlyNum()

    {

    if(!(event.keyCode==46)&&!(event.keyCode==8)&&!(event.keyCode==37)&&!(event.keyCode==39))

        {

        if(!((event.keyCode>=48&&event.keyCode<=57)||(event.keyCode>=96&&event.keyCode<=105)))

            {

            event.returnValue=false;

            }

        }

    }


</script>

<input onkeydown="onlyNum()"/>

設定當keydown這個時間發生時,Event發生的事件這個對象,keyCode是Event對象的一個屬性,該屬性指明了被敲擊的鍵產生的Unicode字元碼

上面的方法解析:

斷行符號:8  Delete:46  方向鍵左:37 方向鍵右:39  

大鍵盤上方 0-9 : 48-57 小鍵盤數字鍵0-9 : 96-105

上面方法的邏輯是:如果不是 ← → backspace delete 就會做判斷 輸入的是不是數字,不是數位話就把Event對象的returnValue屬性設為false,表示取消事件的源元素的預設動作。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.