键盘事件
// 键盘事件加给谁?事件源是谁? // var obox = document.querySelector(".box") // 通过事件对象的属性,得知按下的是哪个按键 document.onkeydown = function(eve){ var e = eve || window.event; if(e.keyCode == 65){ console.log("按下了a键") //按键盘A,控制台输出按下了a键 } console.log(e.keyCode) // 按那个键就输出哪个键对应的万国码值 console.log(e.ctrlKey) console.log(e.shiftKey) console.log(e.altKey)
//ctrl shift alt 都比较特殊,可以用于组合 }
demo:
if(e.keyCode == 13 && e.ctrlKey){ //同时按回车和ctrl send(); // 失去焦点的小方法 otxt.blur(); }
demo:通过方向键控制元素的移动
<!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>Document</title> <style> .box{width:100px;height:100px;background: red;position: absolute;left:0;top:0;} </style> </head> <body> <div class="box"></div> </body> <script> var obox = document.querySelector(".box") document.onkeydown = function(eve){ var e = eve || window.event; var code = e.keyCode || e.which; switch(code){ case 37: // 设置left = 获取当前 - 10 obox.style.left = obox.offsetLeft-10 + "px";break; case 38: obox.style.top = obox.offsetTop-10 + "px";break; case 39: obox.style.left = obox.offsetLeft+10 + "px";break; case 40: obox.style.top = obox.offsetTop+10 + "px";break; } } </script> </html>
长风破浪会有时,直挂云帆济沧海