JavaScript教程:键盘事件

说明

键盘相关事件

事件类型

  • keydown : 当键盘按下时调用,如不松手则反复调用。

    • 非字符输入也调用,如:按下 ctrl、alt、shift 按键就会触发。
    • 用拼音输入法时,可以获取拼音字母
  • keyup : 按下键盘后,松开时调用

  • keypress :当键盘按下时调用,如不松手则反复调用。

    • 非字符输入不调用,如:按下 ctrl、alt、shift 按键就不会触发

以上三个方法都可以在回调函数中通过event.keyCode获取字符码

  • textInput:当键盘按下时调用,如不松手则反复调用。
    • 非字符输入不调用,如:按下 ctrl、alt、shift 按键就不会触发。
    • 通过 e.data 可以获取输入的字符,每次获取一个

案例

用户名: <input type="text" id="username">

<script>

    document.getElementById("price").addEventListener("keydown",function(e){
        console.log("触发keydown事件,keycode:",e.keyCode)
    })
    document.getElementById("price").addEventListener("keyup",function(e){
        console.log("触发keyup事件,keycode:",e.keyCode)
    })
    //可输入按键才会触发
    document.getElementById("price").addEventListener("keypress",function(e){
        console.log("触发keypress事件,keycode:",e.keyCode)
    })
    /*
     * textInput:要有大小写
     */
    document.getElementById("price").addEventListener("textInput",function(e){
        console.log("触发 textinput 事件,data:",e.data)
    })
</script>

原文出处:/show_1IX3B5IMjCzh.html