1. 程式人生 > >鍵盤移動

鍵盤移動

load doc etl char onkeydown top 方向鍵 class asc

/*
* 使div可以根據不同的方向鍵向不同的方向移動
* 按左鍵,div向左移
* 按右鍵,div向右移
* 37 左
* 38 右
* 39 上
* 40 下

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            #box1{
                width
: 100px; height: 100px; background: red; position: absolute; } </style> <script type="text/javascript"> /* * 使div可以根據不同的方向鍵向不同的方向移動 * 按左鍵,div向左移 * 按右鍵,div向右移 * 37 左 * 38 右 * 39 上 * 40 下
*/ window.onload = function(){ //為document綁定按鍵按下的事件 document.onkeydown = function(){ console.log(event.keyCode) event = event || window.event; switch(event.keyCode){
case 37: box1.style.left = box1.offsetLeft-10 +"px"; break; case 38: box1.style.left = box1.offsetLeft+10 +"px"; break; case 39: box1.style.top = box1.offsetTop-10 +"px"; break; case 40: box1.style.top = box1.offsetTop+10 +"px"; break; } } } </script> </head> <body> <div id="box1"> </div> </body> </html>

鍵盤移動