HOWTO · jQuery

jQuery keyup

本教程演示瞭如何在 jQuery 中使用 keyup 事件。

每當從鍵盤上釋放一個鍵時,jQuery 中的 keyup() 方法都會觸發 JavaScript 的 keyup 事件。本教程演示瞭如何在 jQuery 中使用 keyup() 方法。

jQuery Keyup

當從鍵盤上釋放一個鍵時,keyup() 方法將觸發 keyup 事件。該方法用於檢測是否從鍵盤上釋放了任何鍵。

此方法的語法如下。

$(selector).keyup(function)

其中 selector 可以是 id、類或元素名稱,function 是一個可選引數,可以讓我們瞭解是否按下了鍵。該方法的返回值是按鍵是否被按下。

它會根據它改變背景顏色。讓我們嘗試一個 keyup() 方法的示例。

<!DOCTYPE html>
<html>
<head>
    <title>jQuery  keyup() Method</title>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    <script>
    $(document).ready(function(){
        $("input").keydown(function(){
            $("input").css("background-color", "lightblue");
        });
        $("input").keyup(function(){
            $("input").css("background-color", "lightgreen");
        });
    });
</script>
</head>
<body>
    Type Something: <input type="text">
</body>
</html>

上面的程式碼將在鬆開按鍵時將輸入欄位的背景顏色更改為淺綠色,按下按鍵時將其更改為淺藍色。見輸出:

jQuery Keyup 方法

讓我們嘗試另一個示例,該示例將在每次釋放鍵時更改 div 的背景顏色。參見示例:

<html>
<head>
    <title>jQuery  keyup() Method</title>
    <script  src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
    <style>
    div {
        width: 700px;
		height:  500px;
		padding:  30px;
		font-size:  large;
		text-align:  center;
		margin:  auto;
        font-weight: bold;
        border:  5px  solid  cornflowerblue;
		margin-top:  50px;
        margin-bottom:  20px;
    }
    </style>
</head>
    <script>
        var colors = ["lightblue", "lightgreen", "violet", "lightpink", "red", "forestgreen", "white", "indigo"];
        var  i  =  0;
        $(document).keyup(function(event)  {
            $("div").css("background-color",  colors[i]);
			i++;
            i  =  i  %  9;
       });
</script>
<body>
    <br />
    <br />
    <div>
        <h1  style="color:teal;  font-size:x-large;  font-weight:  bold;"> jQuery  keyup  event </h1>
        <p  style="color:maroon;  font-size:  large;">
        Press  and  release the space or any other key <br  /> The background of the div will change </p>
    </div>
</body>
</html>

請參閱上面程式碼的輸出:

jQuery Keyup 方法背景