js_键盘事件
一.定义
键盘事件由用户击打键盘触发,主要有keydown、keypress、 keyup三个事件。
-
keydown:按下键盘时触发。
-
keypress:按下有值的键时触发,即按下 Ctrl、Alt、Shift、Meta 这样无值的键,这个事件不会触 发。对于有值的键,按下时先触发keydown事件,再触发这个事件。
-
keyup:松开键盘时触发该事件
event对象
keyCode:唯一标识
二.实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <input type="text" id="a"> <br> <input type="text" id="pwd"> <input type="text" id="user"> <script> var a = document.getElementById('a'); var pwd = document.getElementById('pwd'); var user = document.getElementById('user'); a.onkeyup = function(e) { console.log(e.target.value); } pwd.onkeypress = function(e) { console.log(e.target.value); } user.onkeyup = function(e) { if(e.keyCode == 13) { console.log('用户按了回车!'); } } </script> </body> </html>