js实现键盘控制小球移动事件keyCode的小练习

注:程序没有设置边框的临界点的值,所以会出去,有待完善

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        #box {
            width: 100px;
            height: 100px;
            background-color: orangered;
            border-radius: 50%;
            position: fixed;
            top: 400px;
            left: 200px;
        }
    </style>
</head>
<body>
<div id="box"></div>
<script>
    var box = document.getElementById('box');
    //设置最大宽度和最大高度
    //var maxWidth = document.documentElement.clientWidth;
    document.onkeydown = function (e) {
        e = e || event;

        //获得小球style
        var style = getStyle(box);
        var keyCode = e.keyCode;

        const LEFT = 37;
        const UP = 38;
        const RIGHT = 39;
        const DOWN = 40;
        
        const SPEED = 5;//速度

        switch (keyCode) {
            case UP:
                box.style.top = parseInt(style.top) - SPEED + 'px';
                break;
            case DOWN:
                box.style.top = parseInt(style.top) + SPEED + 'px';
                break;
            case LEFT:
                box.style.left = parseInt(style.left) - SPEED + 'px';
                break;
            case RIGHT:
                box.style.left = parseInt(style.left) + SPEED + 'px';
                break;
        }
    };

    /**
     * 获得指定样式
     * @param ele
     */
    function getStyle(ele) {
        if (window.getComputedStyle) {//谷歌
            return window.getComputedStyle(ele)
        }
        return ele.currentStyle;//IE
    }


</script>
</body>
</html>

你可能感兴趣的:(js)