当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


JQuery keyup()用法及代码示例


jQuery keyup()是一个内置方法,用于在用户从键盘上释放按键时触发 keyup 事件。因此,使用keyup()方法我们可以检测键盘上是否有按键被释放。

用法:

$(selector).keyup(function) 

这里的selector就是被选择的元素。

参数:它接受一个可选参数作为函数,该函数给出是否按下任何键的想法。

jQuery 示例展示 keyup() 方法的用法原理:
示例 1:下面的代码用于检查按下键盘按键后是否松开。

HTML


<!DOCTYPE html>
<html>
<head>
    <title>Jquery | Keyup() </title>
    <script src=
"https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js">
    </script>
    <script>
        $(document).keyup(function (event) {
            alert('You released a key');
        });
    </script>
</head>
<body>
    <center>
        <h1>
            Press and release a key from the keyboard
        </h1>
    </center>
</body>
</html>

输出:

示例 2:下面的代码用于在键盘释放按键时更改页面的背景颜色

HTML


<!DOCTYPE html>
<html>
<head>
    <title>Jquery | Keyup() </title>
    <script src=
"https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js">
    </script>
    <script>
        let colors = ['red', 'blue', 'green', 'grey',
            'black', 'white', 'teal', 'yellow'];
        let i = 0;
        $(document).keyup(function (event) {
            $('body').css('background-color', colors[i]);
            i++;
            i = i % 9;
        });
    </script>
</head>
<body>
    <center>
        <h3>
            Press any key from the keyboard and then release it <br>
            to change the background color of the page
        </h3>
    </center>
</body>
</html>

输出:



相关用法


注:本文由纯净天空筛选整理自ihritik大神的英文原创作品 jQuery keyup() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。