jQuery keyup

Sheeraz Gul 2022年7月12日
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 方法背景

Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

相关文章 - jQuery Function