Skip to content

键盘事件

事件类型

  • keydown:按下键盘上任意键触发,如果按住不放,会重复触发此事件
  • keypress:按下键盘上一个字符键时触发
  • keyup:抬起键盘上任意键触发

keydown、keypress 如果阻止了事件默认行为,文本不会显示。

事件对象

KeyboardEvent

  • code:得到按键字符串,适配键盘布局。
  • key:得到按键字符串,不适配键盘布局。能得到打印字符。
  • keyCode、which:得到键盘编码

实践

js
var tank = {
    direction: "U",// U L R D
    left: 500,
    top: 400,
    dom: document.querySelector("img"),
    show: function () { //显示
        this.dom.style.left = this.left + "px";
        this.dom.style.top = this.top + "px";
        this.dom.src = "imgs/tank" + this.direction + ".gif";
    }
}

//切换方向 和 移动
document.addEventListener("keydown", function (e) {
    if (e.key === "ArrowUp") {
        tank.direction = "U";
        tank.top -= 4;
    }
    else if (e.key === "ArrowDown") {
        tank.direction = "D";
        tank.top += 4;
    }
    else if (e.key === "ArrowLeft") {
        tank.direction = "L";
        tank.left -= 4;
    }
    else if (e.key === "ArrowRight") {
        tank.direction = "R";
        tank.left += 4;
    }
    tank.show();
})
js
    var inp = document.querySelector("input");
    inp.onkeypress = function(e) {
        var code = e.key[0].charCodeAt(0);
        if (code < 48 || code > 57) {
            e.preventDefault();
        }
    }

    inp.onpaste = function(e) {
        var text = e.clipboardData.getData("text/plain");
        if (!text || !/\d+/.test(text)) {
            e.preventDefault();
        }
    }

MIT License