Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/374.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ms-access/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript:使用箭头键移动对象_Javascript_Html_Css - Fatal编程技术网

Javascript:使用箭头键移动对象

Javascript:使用箭头键移动对象,javascript,html,css,Javascript,Html,Css,我正在做一个简单的俄罗斯方块游戏。到目前为止,我有一个俄罗斯方块,当点击空格键时它会旋转 我的下一步是使用箭头键左右移动对象。从其他方面看,我发现通过改变利润率,这是可能的 var angle = 0; var obj = document.getElementById('image') document.onkeydown = checkKey; function checkKey(e) { e =

我正在做一个简单的俄罗斯方块游戏。到目前为止,我有一个俄罗斯方块,当点击空格键时它会旋转

我的下一步是使用箭头键左右移动对象。从其他方面看,我发现通过改变利润率,这是可能的

        var angle = 0;
        var obj = document.getElementById('image')

        document.onkeydown = checkKey;

        function checkKey(e) {

            e = e || window.event;

            if (e.keyCode == '32') {
                rotate();
            }
            else if (e.keyCode == '37') {
                moveLeft();
            }
            else if (e.keyCode == '39') {
                moveRight();
            }

        }
        function rotate() {
            angle = angle + 90;
            console.log(angle)
            obj.className = "image" + angle;
            console.log(obj.className)
            if (angle == 360) {
                angle = 0;
            }
        }

        function moveLeft() {
            obj.style.left = parseInt(obj.style.left) - 5 + 'px';
        }

        function moveRight() {
            obj.style.left = parseInt(obj.style.left) + 5 + 'px';
        }
出于某种原因,这对我不起作用


我还用香蕉而不是俄罗斯方块重新创建了我的代码。

问题不在于你的Javascript,而在于你的风格。您需要绝对定位图像(在本例中为香蕉),并设置初始“左”值。
位置:绝对位置
可以在HTML或CSS中设置,但是
左侧:0必须在HTML样式属性中设置。这是一个更新后的图像。

尝试对#图像使用绝对或固定定位,否则左右属性将不会产生任何效果