键盘事件练习——移动的方块

时间:2022-11-29 17:50:39

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8" />
        <title></title>
        <style type="text/css">
            * {
                margin: 0;
                padding: 0;
            }
        </style>
    </head>

    <body style="position: relative;">
        <div id="box" style="width: 100px;height: 100px;background-color: sandybrown;position: absolute;">

        </div>
        <script type="text/javascript">

/*获取浏览器的最大化尺寸*/ var wi = document.documentElement.clientWidth - 100; //取得浏览器页面可视区域的宽度,(并且需要减去 方块的宽度) var hi = document.documentElement.clientHeight - 100; //取得浏览器页面可视区域的高度,(并且需要减去 方块的高度) var box = document.getElementById("box") document.addEventListener("keydown", function(e) { var l = parseInt(window.getComputedStyle(box, null).left); //获取方块坐标 var t = parseInt(window.getComputedStyle(box, null).top); console.log(l, t) var event = e || window.event if(event.key == "w" & t > 0) { box.style.top = t - 10 "px"; }; if(event.key == "s" & t < hi) { box.style.top = t 10 "px"; }; if(event.key == "a" & l > 0) { box.style.left = l - 10 "px"; }; if(event.key == "d" & l < wi) { box.style.left = l 10 "px"; }; }, false) </script> </body> </html>