【发布时间】:2021-02-04 10:41:46
【问题描述】:
我开始使用 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>
【问题讨论】:
-
它将是
getElementById而不是getElementbyId。 -
谢谢!想知道为什么编辑不选择这个并标记....解决了,谢谢
-
@Compoot 是的,我想知道他们为什么关闭它,对于 setTimeout 等仍然有效的问题,并且它适合初学者问...
-
非常感谢您的帮助 - 谢谢!
-
@bluejayke - 如果你有兴趣,我的同事(和我一样)也发布了这个! stackoverflow.com/questions/66048374/…
标签: javascript html css settimeout