2017-01-03 91 views
0

我是JS的新手,所以如果有一些简单的答案,我会提前道歉!我已经通过线程和谷歌一小时所以,我没有找到任何东西:(使用箭头键在js div内移动图像

我想要做一个超级马里奥式的游戏,我将字符左右移动。我已经尝试过这样做(创建一个基于方向键移动的方块)。正方形很容易,因为您可以获得它的x和y位置。但是,我已经切换到使用图像,并且我不知道如何使其向左或向右移动

这是我的html文件:

<body> 
    <div id = "char"> 
     <canvas id="myCanvas" width="400" height="400"></canvas> 
     <script src="testing.js"></script> 
    </div> 
</body> 

而这就是我想在JS做:

var img = new Image(), 
    pic = document.getElementById("char"), 
    switchVar=true; 
pic.appendChild(img); 
img.src = "2.png"; 
function move(e) { 
    "use strict"; 
    var x = e.which || e.keycode; //gets the keycode that the user types 

    switch(x) { 
     case 39: 
      //What do I do here?? 
      //the following doesn't work: 
      //pic.style.left = parseInt(pic.style.left) + 100 + 'px'; 
      break; 
    } 
} 
document.onkeydown = move; 

我没有在交换机中包含所有的情况,但是我的代码有左,下和上的情况。另外,我在JS中追加图像的原因是因为我试图在从左到右运行时切换图像(从右腿伸展的人的img切换到左腿伸展的人的图像)

回答

0

您的图片必须

position: absolute; 

由于左,上,右,下只适用于绝对位置。

pic.appendChild(img); 
img.src = "2.png"; 
img.style.position = 'absolute'; 

而且,如果您希望与div #char相关的图片移动div必须具有相对位置。

#char{position:relative;}