jQuery keydown() 事件方法



jQuery 事件keydown() 方法用於附加或繫結事件處理程式到 keydown 事件,該事件在按下鍵盤上的任何鍵時觸發。

語法

以下是 jQuery 事件keydown() 方法的語法:

$(selector).keydown(function)

引數

此方法接受一個可選引數“函式”,如下所述:

  • 函式 - 一個可選函式,在 keydown 事件發生時執行。

返回值

此方法沒有返回值。

示例 1

以下程式演示了 jQuery 事件keydown() 方法的用法:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
</head>
<body>
    <p>Press the down key on your laptop or computer keyboard.</p>
    <script>
        $(document).keydown(function(event){
            alert("You pressed downkey on your keyboard.");
        });
    </script>
</body>
</html>

輸出

執行程式後,每當使用者按下系統鍵盤上的任何鍵時,瀏覽器螢幕上都會出現一個警報彈出訊息:


當用戶按下系統鍵盤上的任何鍵時:


示例 2

以下示例演示了 jQuery keydown() 方法的使用。此方法用於將事件處理程式繫結到輸入元素的 keydown 事件。當用戶開始在輸入欄位中鍵入時,將觸發 keydown 事件,並在輸入欄位中以“紅色”顯示輸入的文字:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
</head>
<body>
    <p>Write something in the below input field and press any key.</p>
    <input type="text" placeholder="Your name">
    <script>
        $('input').keydown(function(){
            $(this).css("color", "red");
        });
    </script>
</body>
</html>

輸出

執行程式後,將顯示一個輸入欄位。當用戶開始在欄位中鍵入任何內容時,文字將以紅色顯示在輸入欄位中:


當用戶在輸入欄位中輸入內容時:


示例 3

使用 jQuery keydown() 方法進行表單驗證

讓我們演示 jQuery keydown() 方法的即時應用。我們將建立一個包含兩個輸入欄位的表單。每當使用者開始在任何輸入欄位中鍵入時,都會觸發 keydown() 事件。

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<style>
    input{
        display: block;
        margin: 10px 0px;
        padding: 10px;
        width: 200px;
    }
</style>
</head>
<body>
    <p>Write something in the below input field </p>
    <form>
        <input type="text" placeholder="Username" id="uname">
        <input type="password" placeholder="Password" id='psw'>
    </form>
    <script>
        $('input').keydown(function(){
            let uname = $('#uname').val();
            let password = $('#psw').val();
            if(uname.length == 5 | password.length  == 8){
                $(this).css("background-color", "green");
            }
            else{
                $(this).css("background-color", "red");
            }
        });
    </script>
</body>
</html>

輸出

執行程式後,將顯示一個包含兩個輸入欄位的表單。如果任一輸入欄位的值長度不等於 5 或 8,則該輸入欄位的背景顏色將顯示為紅色;否則,將變為綠色:


如果輸入的內容不滿足給定條件:


如果輸入的內容正確且滿足給定條件:


jquery_ref_events.htm
廣告