两者的区别
1.表示的意义不同。onkeyup键盘抬起事件,onkeydown键盘按下事件
2.触发时机不同。onkeyup 事件会在键盘按键被松开时发生。onkeydown 事件会在用户按下一个键盘按键时发生。
3.监听的值不同。onkeyup监听的是本次的结果,onkeydown监听的是上一次的结果。
实例如下:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta http-equiv="X-UA-Compatible" content="ie=edge" /><title>键盘事件</title></head><body><input type="text" id="txt" onkeydown="downHandle(event)" onkeyup="upHandle(event)" /><script>var txtInput = document.querySelector('#txt')function downHandle(e) {console.group('按下')console.log(txtInput.value)console.groupEnd()}function upHandle(e) {console.group('抬起')console.log(txtInput.value)console.groupEnd()}</script></body></html>
在输入框中依次输入1,2;结果如下: