首页 > 解决方案 > JavaScript 跳转功能失败,找不到错误

问题描述

我开始使用 JavaScript、CSS 和 HTML 编写一个简单的游戏,并且在我创建了一个跳转功能之前,该游戏一直在运行。OnClick,字符元素(由css生成为绿色矩形)应该跳转。相反,它是静态的,不会移动。

最初,我有这个代码:

.animate{
    animation: jump 500ms;
}

在角色的 CSS 中,它在没有任何用户交互的情况下连续跳跃。

我做错了什么?我认为这与此有关:

 function jump(){
        character.classList.add("animate");
        setTimeout(function(){
            character.classList.remove("animate");
        },500);
    }

对于答案,我希望指出错误,并提供新代码和关于 setTimeout 函数如何工作的清晰解释。setTimeout 是现有的内置方法吗?如果是,我们在哪里可以找到有关这些内容的文档?

代码

var character = document.getElementById("character");
var enemy = document.getElementById("enemy");

//adding the animate function in the css here, so it is applied to our character
function jump() {
  character.classList.add("animate");
  setTimeout(function() {
    character.classList.remove("animate");
  }, 500);
}
* {
  padding: 0;
  margin: 22;
}

#game {
  width: 500px;
  height: 500px;
  border: 1px solid #319b4e;
}

#character {
  width: 30px;
  height: 120px;
  background-color: green;
  position: relative;
  top: 380px;
  border-radius: 20px;
  /*animation: jump 500ms */
}


/* new class called animate */

.animate {
  animation: jump 500ms;
}

#enemy {
  width: 60px;
  height: 60px;
  background-color: red;
  border-radius: 14px;
  position: relative;
  top: 320px;
  left: 440px;
  animation: moveenemy 1s infinite linear;
}

@keyframes moveenemy {
  0% {
    left: 440px;
  }
  50% {
    top: 58px;
  }
  100% {
    left: 0px;
    top: 320x;
  }
}

@keyframes jump {
  0% {
    top: 380px;
  }
  30% {
    top: 200px;
  }
  50% {
    top: 200px;
  }
  100% {
    top: 380px;
  }
}
<!DOCTYPE html>

<html lang="en" onclick="jump()">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <link rel="stylesheet" href="style.css">

</head>

<body>
  <h1>Game</h1>
  <p>My first ever game</p>
  <p>We all have an enemy</p>


  <div id="game">

    <div id="character"></div>
    <div id="enemy"></div>

  </div>
  <script src="script.js"></script>
</body>

</html>

标签: javascripthtmlcsssettimeout

解决方案


setTimeout 是现有的内置方法吗?如果是,我们在哪里可以找到有关这些内容的文档?

setTimeout 函数的工作原理

  • 因此,setTimeout方法接受一个函数/代码和一个延迟(以毫秒为单位),之后它将执行它。参考上面的链接。

它将事件带入事件循环,使其异步调用。

我会在一段时间后查看代码并回复您!:D

收藏 MDN Web Docs,真的很方便!


推荐阅读