为什么我的css动画会成倍地变小,并最终停止工作



我正在制作一个小游戏,其中一个方块向角色滑动,通过鼠标点击游戏主体,角色就会跳过方块。每当我刷新页面时,它都能正常工作,但点击几下后,动画就会变得越来越小(距离是跳跃和动画完成所需的时间(,最终完全停止工作。我已经包含了一个代码片段,这样你就可以看到问题了。

let character = document.getElementById('character');
let obstacle = document.getElementById('obstacle');
function jump() {
if (character.classList != 'animate') {
character.classList.add('animate');
}
setInterval(function () {
character.classList.remove('animate');
}, 500);
}
* {
padding: 0;
margin: 0;
}
.game {
height: 200px;
width: 500px;
border: 5px solid black;
}
@keyframes jump{
0%{top: 150px;}
30%{top: 100px;}
70%{top: 100px;}
100%{top: 150;}
}
.character {
height: 50px;
width: 20px;
background-color: red;
position: relative;
top: 150px;
}
.animate {
animation: jump 0.5s;
}
@keyframes block{
0%{left: 480px;}
100%{left: -40px;}
}
.obstacle {
height: 20px;
width: 20px;
background-color: blue;
position: relative;
top: 130px;
left: 480px;
animation: block 2s  infinite linear;
}
<!DOCTYPE html>
<html>
<head>
<title>Jumping Game</title>
<link rel="stylesheet" href="jump.css">
</head>
<div>
<body onclick="jump()">
<div class="game">
<div id="character" class="character">
</div>
<div id="obstacle" class="obstacle">
</div>
</div>
</body>
</div>
<script src="jump.js"></script>
</html>

因为您使用setInterval,它以500ms的间隔重复执行提供给它的函数,直到您用clearInterval停止它(传递从初始setInterval调用返回的超时id(。

如果您只想在500ms后执行一次功能,请使用setTimeout:https://jsfiddle.net/dp0n8Leh/(如果您足够早地点击,请确保您在前一次超时时首先使用clearTimeout(

此外,要检查元素是否有类,应该使用!character.classList.contains('animate')而不是character.classList != 'animate'

只使用setTimeout而不是setInterval来删除类

最新更新