恐龙游戏添加jump类后CSS跳跃动画未触发问题求助
恐龙游戏跳跃动画不执行问题解决
问题核心
按下任意按键后,dino元素已成功添加jump类,但对应的CSS跳跃动画未执行,需要实现按键触发恐龙跳跃的效果。
问题原因
- CSS优先级冲突:
#dino选择器的animation属性(跑步动画)权重高于.jump类选择器,导致跳跃动画被覆盖,无法生效。 - JavaScript类判断逻辑错误:
dino.classList != "jump"的写法不成立,classList是DOMTokenList对象,不能直接与字符串比较,会导致重复添加类的问题,影响动画触发。 - 跳跃动画关键帧逻辑异常:当前关键帧中50%位置的
top: 180px会让恐龙向下偏移,不符合正常跳跃的视觉轨迹。
修复方案
1. 调整CSS选择器优先级
将.jump类选择器改为#dino.jump,利用ID+类的更高权重覆盖跑步动画,同时在跳跃时临时暂停跑步动画:
#dino.jump { animation: jump 0.3s linear; /* 跳跃时暂停跑步动画 */ animation-play-state: paused; }
2. 修正JavaScript类判断逻辑
使用classList.contains()方法判断是否存在jump类,避免重复添加导致动画无法重新触发:
function jump() { if (!dino.classList.contains("jump")) { dino.classList.add("jump"); } setTimeout(function () { dino.classList.remove("jump"); // 移除跳跃类后恢复跑步动画 dino.style.animationPlayState = "running"; }, 300); }
3. 优化跳跃动画关键帧
调整关键帧的top值,让恐龙先向上跳跃再自然下落:
@keyframes jump { 0% { top: 150px; } 30% { top: 100px; } 50% { top: 80px; } 80% { top: 100px; } 100% { top: 150px; } }
完整修正后代码
HTML代码(不变)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Dino game</title> <link rel="stylesheet" href="style.css" /> </head> <body> <div class="game"> <div id="dino"></div> <div id="cactus"></div> </div> <script src="index.js"></script> </body> </html>
JavaScript代码(修正后)
const dino = document.getElementById("dino"); const cactus = document.getElementById("cactus"); document.addEventListener("keydown", function (event) { jump(); }); function jump() { if (!dino.classList.contains("jump")) { dino.classList.add("jump"); } setTimeout(function () { dino.classList.remove("jump"); dino.style.animationPlayState = "running"; }, 300); }
CSS代码(修正后)
.game { width: 600px; height: 200px; border-bottom: 1px solid #000000; margin: auto; overflow: hidden; } #dino { width: 50px; height: 50px; background-image: url(/image/dino/run1.png); background-size: 50px 50px; position: relative; top: 150px; animation: run 0.3s infinite linear; } @keyframes run { 0% { background-image: url(/image/dino/run1.png); } 50% { background-image: url(/image/dino/run2.png); } 100% { background-image: url(/image/dino/run3.png); } } #cactus { width: 20px; height: 40px; background-image: url(/image/cactus/cactus.png); background-size: 20px 40px; position: relative; top: 110px; left: 580px; animation: cactusMov 1s infinite linear; } @keyframes cactusMov { 0% { left: 580px; } 100% { left: -20px; } } #dino.jump { animation: jump 0.3s linear; animation-play-state: paused; } @keyframes jump { 0% { top: 150px; } 30% { top: 100px; } 50% { top: 80px; } 80% { top: 100px; } 100% { top: 150px; } }
内容的提问来源于stack exchange,提问作者Eugene
相关产品推荐
相关产品推荐

