javascript - 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>
解决方案
setTimeout 是现有的内置方法吗?如果是,我们在哪里可以找到有关这些内容的文档?
- 是的,
setTimeout
是一种内置方法。你可以在这里MDN Web Docs了解更多信息。
setTimeout 函数的工作原理
- 因此,
setTimeout
方法接受一个函数/代码和一个延迟(以毫秒为单位),之后它将执行它。参考上面的链接。
它将事件带入事件循环,使其异步调用。
我会在一段时间后查看代码并回复您!:D
收藏 MDN Web Docs,真的很方便!
推荐阅读
- html - 如何让音频在css中正确浮动
- c - 有没有办法不处理“#include”指令而只处理#if、#ifdef 等?
- java - 线程“主”java.util.Input MismatchException 中的异常
- vb.net - 使用 Regex 删除任何重复的内容
- spring - Spring Boot:在“应用程序运行失败”时退出 jvm
- node.js - react-apollo 错误:[网络错误]:ServerParseError:JSON.parse:JSON 数据的第 1 行第 1 列出现意外字符
- laravel - 从自定义字段更新同级输入字段
- jupyter-notebook - 为什么我的光标在 Jupyter Notebook 中偏移?
- node.js - 循环 json 数据并将项目添加到 DynamoDB
- python - CUDA 在推理过程中内存不足并给出 InternalError: CUDA 运行时隐式初始化 GPU:0 失败。状态:内存不足