今天来给大家讲一讲dom 的键盘事件:
键盘事件分为这几种:
onkeydown 、onkeyup 、
键盘的属性有这一种:
keycode
先来说说键盘的事件:
onkeydown 指的是键盘上的键按下去的一瞬间执行的代码,例如:
document. onkeydown =function (){
alert (1);
}
onkeyup 指的是键盘上的键弹起来的一瞬间执行的代码,例如:
document. onkeyup =function (){
alert (1);
}
keycode 指的是按下去或弹起来的那个键的代码数值,例如:A 是65,B 是66,C 是67…ESC 退出键是63…
document. onkeydown =function (e ){
if (e. keycode ==63){
alert ("按下去了ESC 键") ;
}
}
同理document. onkeyup =function (e ){
if (e. keycode ==63){
alert ("弹起来了ESC 键");
}
}
来写一个有关的键盘事件的案例:
这里有一个键A ,按下去的时候出现灰色盒子,弹起来的时候隐藏灰色盒子,我们平常看到的按任意键退出,按ESC 键退出主屏幕,不能复制剪切粘贴等现象都是通过这样的一串代码实现的。请看下面的这个案例:
#box {width: 200px; height: 200px; background-color: #ccc; }
var dis =document. body. createElement (div);
document. onkeydown =function (e ){
if (e. keycode ==65){
dis. setAttribute (id, box );
document. body. appendchild (dis);
}
}
document. onkeyup =function (e){
if (e.keycode ==65){
document. body. removeChild(dis);
}
这样就能实现按键A 的按下与弹起来的功能的一个切换。喜欢这篇原创吗?请给我点个赞再走吧!谢谢啦啊,各位大佬们!🤓