jQuery按键事件

时间:2020-02-23 14:46:11  来源:igfitidea点击:

jQuery keypress是键盘事件方法之一。
其他jQuery键盘事件方法是keyup和keydown。

jQuery按键

jQuery keypress方法使用javascript的按键事件触发。
由于此事件在不同的浏览器中会有所不同,因此任何正式规范均未涵盖。
此事件仅针对焦点元素触发。
跨不同的浏览器可能会有所不同。

jQuery keypress方法语法

  • keypress():此jQuery keypress方法使用时不带任何参数。

  • keypress(handler):此jQuery keypress方法附加了一个在触发keypress事件时要执行的功能。

jQuery按键示例

以下示例演示了jQuery keypress方法的使用。

jquery-keypress.html

<!DOCTYPE html>
<html>
<head>
<title>jQuery keypress event example</title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
$(document).ready(function(){
$("input:text").keyup(function(){
  $("input:text").css("background-color","red");
});
$("input:text").keypress(function(){
  $("input:text").css("background-color","yellow");
});
//reset jQuery keydown css
$("input:reset").click(function(){
  $("input:text").css("background-color","white");
});
});
</script>
</head>
<body>
<h3>jQuery keypress example</h3>
Enter anything: <input type="text">
<input type="reset">
<br>
Type something above, background colour will change to yellow on key press.
<br>
Click on Reset button to try again.
</body>
</html>

在上面的示例中,当按下键时,将触发keypress()方法,该方法又执行将背景色更改为黄色的功能。