尝试使div在键盘按下时在屏幕上移动

时间:2019-03-02 07:41:24

标签: javascript html css html5 webpage

我正在尝试制作一款游戏,玩家必须在迷宫中导航鼠标以找到奶酪块。我在让div移动我想要的方式时遇到了一些麻烦。问题是当您按下向下箭头键(我正在用来测试它的键)时,它不会像我想要的那样以10为增量不断下降。我已经尝试过循环,但整个过程都如此,但我只是想不通如何使之工作。

document.onkeydown = function(key){
    if (key.keyCode == 38){
        console.log("up");
    } else if (key.keyCode == 39){
        console.log("right");
    } else if (key.keyCode == 37){
        console.log("left");
    } else if (key.keyCode == 40){
        mouse.style.top = 10 + "px";
    };
};

3 个答案:

答案 0 :(得分:2)

您可以使用Player对象并修改其xy属性。
还创建一个K对象,将当前使用的数字设置为布尔值。
比像requestAnimationFrame这样的循环内移动播放器:

const Player = {
  el: document.getElementById('mouse'),
  x: 200,
  y: 100,
  speed: 2,
  move() {
    // If no collision with map or tiles... (TODO!)
    this.el.style.transform = `translate(${this.x}px, ${this.y}px)`;
  }
};
 
const K = {
  fn(ev) {
    ev.preventDefault();
    const k = ev.which;
    if (k >= 37 && k <= 40) K[k] = ev.type === "keydown"; // If is arrow
  }
};
  
const update = () => {
    // 1 / Math.sqrt(2) = 0.7071.. (Diagonal)
    let dist = K[38] && (K[37] || K[39]) || K[40] && (K[37] || K[39]) ? 0.707 : 1;
    dist *= Player.speed;
    if (K[37]) Player.x -= dist;
    if (K[38]) Player.y -= dist;
    if (K[39]) Player.x += dist;
    if (K[40]) Player.y += dist;
    Player.move();
}

document.addEventListener('keydown', K.fn);
document.addEventListener('keyup', K.fn);

(function engine() {
  update();
  window.requestAnimationFrame(engine);
}());
#mouse{
  position: absolute;
  left: 0;  top: 0;
  width: 20px;  height: 20px;
  background: #000;  border-radius: 50%;
}
Click here to focus, and use arrows
<div id="mouse"></div>


一个更简单的示例,只要按住键(就像键入一样),该元素就会以 Npx 个步骤移动并重复:

const Player = {
  el: document.getElementById('mouse'),
  x: 0,
  y: 0,
  step: 10,
  move() {
    this.el.style.transform = `translate(${this.x}px, ${this.y}px)`;
  }
};

const keysHandler = (ev) => {
  const k = ev.which;
  if (k>=37 && k<=40) {
    ev.preventDefault();
    ({
      '37' () {Player.x -= Player.step},
      '38' () {Player.y -= Player.step},
      '39' () {Player.x += Player.step},
      '40' () {Player.y += Player.step},
    }[k]());
    Player.move();
  }
}

document.addEventListener('keydown', keysHandler);
#mouse{
  position: absolute;
  left: 0;  top: 0;
  width: 20px;  height: 20px;
  background: #000;  border-radius: 50%;
}
Click here to focus, and use arrows
<div id="mouse"></div>

答案 1 :(得分:0)

您每次都将其设置为10,请使用else if (key.keyCode == 40){ mouse.style.top = parseInt(mouse.style.top.split("px")[0]) + 10 + "px"; } 首先获取该值:

df['newid'] = df['date'].dt.strftime('%Y%m%d')+(df.groupby([df['date'].dt.date,'id']).cumcount()+1).astype(str).str.zfill(6) + '-A'
print(df)

# print
                 date  id             newid
0 2019-01-01 10:00:00   1  20190101000001-A
1 2019-01-01 11:00:00   1  20190101000002-A
2 2019-01-01 12:00:00   1  20190101000003-A
3 2019-01-01 19:00:00   2  20190101000001-A
4 2019-01-02 09:00:00   2  20190102000001-A
5 2019-01-02 10:00:00   2  20190102000002-A
6 2019-01-05 15:00:00   3  20190105000001-A

答案 2 :(得分:0)

即使其他答案使用了parseInt,也最好将变量保留在代码中

var x = 0;
var y = 0;

document.onkeydown = function(key){
    if (key.keyCode == 38){
        y -= 10;
    } else if (key.keyCode == 39){
        x += 10;
    } else if (key.keyCode == 37){
        x -= 10;
    } else if (key.keyCode == 40){
        y += 10;
    };
    
    document.getElementById("block").style.left = x+"px";
    document.getElementById("block").style.top = y+"px";
};
#block
{
  top: 0;
  left: 0;
  position: absolute;
  width: 30px;
  height: 60px;
  background: teal;
}
<div id="block">