CSS动画仅重新保存style.css后生效,后续操作无动画问题求助
温度条形动画问题:首次无效果/后续直接跳转的修复方案
问题核心原因
你的代码存在两个关键疏漏:
- 首次输入时,浏览器渲染优化导致动画触发时机异常,无法识别初始状态到目标状态的过渡;
- 后续输入时,动画类
slide-to-temp未被重置,CSS动画默认仅执行一次,因此直接跳转到目标高度; --temp-start变量未随每次动画结束更新,导致后续动画始终从初始0%开始,逻辑不符合预期。
修复方案
以下是调整后的完整代码,解决上述所有问题:
修改后的JavaScript代码
let indicator = document.getElementById("indicator-1"); let root = document.documentElement; function changeTemp() { let inputTemp = prompt("Enter a temp:"); // 过滤无效输入 if (!inputTemp || isNaN(inputTemp)) return; // 将起始值设为当前指示器的实际高度百分比 const containerHeight = indicator.parentElement.offsetHeight; const currentHeightPercent = (indicator.offsetHeight / containerHeight) * 100; root.style.setProperty("--temp-start", `${currentHeightPercent}%`); // 设置目标高度 root.style.setProperty("--temp-end", `${inputTemp * 2}%`); // 重置动画:先移除类,等待浏览器重排后再添加,强制触发动画 indicator.classList.remove("slide-to-temp"); requestAnimationFrame(() => { indicator.classList.add("slide-to-temp"); }); }
CSS代码(无需大幅修改,仅保留原有逻辑即可)
:root { --temp-start: 0%; --temp-end: 0%; } .wrapper{ display: flex; flex-direction: column; justify-content: center; align-items: center; gap: 50px; } .temp-container { width: 50px; height: 500px; margin: 50px 0px; background: black; position: relative; display: flex; flex-direction: column; justify-content: flex-end; border-radius: 25px; } .temp-indicator { width: 100%; mask:linear-gradient(#fff 0 0); border-radius: 25px; } .slide-to-temp { animation: slideToTemp 1s forwards; } @keyframes slideToTemp { from {height: var(--temp-start);} to {height: var(--temp-end);} } .temp-indicator::before { content:""; position: absolute; top:0; left:0; right:0; bottom:0; background-image: linear-gradient(red, lightblue 75%); } #indicator-1 { height: var(--temp-start); } button { padding: 20px; font-size: 20px; font-weight: 800; border: 5px solid black; }
关键修复点说明
- 同步起始高度:通过计算当前指示器高度与容器高度的比例,动态更新
--temp-start,确保动画从当前状态平滑过渡到目标状态; - 强制触发动画:使用
requestAnimationFrame延迟添加动画类,让浏览器有时间处理DOM重排,避免因类的快速移除/添加被优化掉; - 无效输入处理:添加判断过滤非数字输入,避免程序报错。
内容的提问来源于stack exchange,提问作者CodingNewbie
相关产品推荐
相关产品推荐

