我如何在js中使桨移动

How do I make a paddle move in js

如何使用 JS 移动此框我试图让我的函数指向一个函数,但它不会指向它。

我尝试使用 call 方法调用该函数,然后尝试使用 apply 方法。

我还有一个动画在 CSS 中工作,我想知道我是否正确地在 JS 中创建了动作。

console.log("hi");
var animation = {
  move: function BoxRight(elem, pos, id) {
    return this.elem1 + this.pos + this.id;
  }
};

var elem1 = document.getElementById("RightAnimate");
var pos = 0;
var id = setInterval(animation.frame, 5000);
var x = function frame() {
  if (pos == 350) {
    clearInterval(id);
  } else {
    pos++;
    elem1.style.top = pos + "px";
    elem1.style.left = pos + "px";
  }
};

function arrowFunction(event) {
  var x = event.key;
  console.log(x);
  if (x == "ArrowLeft") {
    alert("You pressed the 'left' key!");
  }
  // You had an extra slash here
  // I want to call it down here!!
  // this is the issue

  if (x == "ArrowRight") {
    animation.BoxRight.call(elem1, 0, id);

    function frame() {
      return this;
    }
  }
}
  body {
  font-family: helvetica, arial, sans-serif;
  margin: 2em;
}

h1 {
  font-style: italic;
  color: #373fff;
}

#Right-animate {
  width: 100px;
  height: 100px;
  background-color: deeppink;
  position: absolute;
}

@-webkit-keyframes move-right {
  0% {
    background-color: red;
    right: 0px;
    top: 0px;
  }
  25% {
    background-color: yellow;
    right: 200px;
    top: 0px;
  }
<!DOCTYPE html>
<html lang="en">

<head>
  <title>Hello!</title>
  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
</head>

<body>
  <div id="container">
    <!-- You are missing the end quote here. Also need a tabindex -->
    <div id="Right-animate" onkeydown="arrowFunction(event)" tabindex="0"></div>
  </div>
</body>

</html>

不太清楚您要做什么。我将假设您想要动画 div 以响应按键。

这是一个使用 CSS 动画实现此目的的简化示例:

const offsetDistance = 50;
const div = document.getElementById('Right-animate');
let offset = { x: 0, y: 0 };

document.body.addEventListener('keydown', event => {
  if (event.key === 'ArrowLeft') {
    offset.x -= offsetDistance;
  } else if (event.key === 'ArrowRight') {
    offset.x += offsetDistance;
  } else if (event.key === 'ArrowUp') {
    offset.y -= offsetDistance;
  } else if (event.key === 'ArrowDown') {
    offset.y += offsetDistance;
  }
  div.style.transform = `translate(${offset.x}px, ${offset.y}px)`;
});
#Right-animate {
  width: 100px;
  height: 100px;
  background-color: deeppink;
  position: absolute;
  transition: transform 0.5s;
}
<div id="Right-animate"></div>