学习javaScript代码之开动的小汽车

学习javaScript代码之开动的小汽车

这两天通过学习自己写了一小段代码,望指教!

<!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>奔跑的小汽车</title>
    <link rel="stylesheet" href="test.css">
    <script type="text/javascript" src="test.js"></script>
</head>
<body>
    <div id="box">
        <img src="img/car.png" alt="">
    </div>
</body>
</html>
#box {
    position: absolute;
    left: 200px;
    top: 150px;
}
#box img{
    width: 100px;
    height: 100px;
}
window.onload = function () {
    var box = document.getElementById('box');
    document.onkeydown = function(e) {
        var e = window.event || e;
        switch(e.keyCode)
        {
            case 37:
            box.style.transform = "rotate(-90deg)";
            box.style.left = box.offsetLeft - 10 + 'px';
            break;

            case 38:
            box.style.transform = "rotate(0deg)";
            box.style.top = box.offsetTop - 10 + 'px';
            break;

            case 39:
            box.style.transform = "rotate(90deg)";
            box.style.left = box.offsetLeft + 10 + 'px';
            break;

            case 40:
            box.style.transform = "rotate(180deg)";
            box.style.top = box.offsetTop + 10 + 'px';
            break;
        }
    };
};

学习javaScript代码之开动的小汽车