JS中的onkeypress和onkeydown

JS中的onkeypress和onkeydown

今天在做一个点击键盘触发事件的小例子,在实现过程中由于没有搞清楚onkeypress和onkeydown的区别,简单的问题花半天才解决,花了不少时间爬坑。

源码如下:

    <input id="name" type="text">    
    <button id="submit-btn">Submit</button>
    <script>
        var btn = document.getElementById('submit-btn');
        btn.onclick = function(){
            var inputText = document.getElementById('name').value;  
            console.log(inputText);
        }
        document.onkeydown = function getKey(){
            if(event.keyCode == 13){  
                var inputText = document.getElementById('name').value;  
                console.log(inputText); 
            }   
            if(event.keyCode == 27){
                var inputText = document.getElementById('name');
                inputText.value = "";
                inputText.focus();   
            }
        }
    </script>

onkeypress 和 onkeydown是有区别的,用的时候请注意,区别如下:

具体区别

  1. 一个放开一个没有放开,onkeydown 先于 onkeypress 发生, onkeyup 是在用户放开任何先前按下的键盘键时发生。
  2. onkeypress 无法识别系统按钮。用户按下并放开任何字母数字键时发生。系统按钮(例如,箭头键和功能键)无法得到识别
  3. onkeydown 捕获的 keyCode 不区分字母大小,而 onkeypress 区分。 用户按下任何键盘键(包括系统按钮,如箭头键和功能键)时发生。

onkeypress

As of Microsoft® Internet Explorer 4.0, the onkeypress event fires and can be canceled for the following keys:

Letters: A - Z (uppercase and lowercase)
Numerals: 0 - 9
Symbols: ! @ # $ % ^ & * ( ) _ - + = < [ ] { } , . / ? \ | ’ ` ” ~
System: ESC, SPACEBAR, ENTER

onkeydown
As of Microsoft® Internet Explorer 4.0, the onkeydown event fires for the following keys:

Editing: DELETE, INSERT
Function: F1 - F12
Letters: A - Z (uppercase and lowercase)
Navigation: HOME, END, LEFT ARROW, RIGHT ARROW, UP ARROW, DOWN ARROW
Numerals: 0 - 9
Symbols: ! @ # $ % ^ & * ( ) _ - + = < [ ] { } , . / ? \ | ’ ` ” ~
System: ESC, SPACEBAR, SHIFT, TAB

参考文档:

https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onkeypress

扫描二维码关注公众号,回复: 1731733 查看本文章

猜你喜欢

转载自blog.csdn.net/weixin_39611130/article/details/80543321